diff --git a/.github/workflows/frontend-qa.yml b/.github/workflows/frontend-qa.yml index 2ba55f59fb..f607760564 100644 --- a/.github/workflows/frontend-qa.yml +++ b/.github/workflows/frontend-qa.yml @@ -5,7 +5,42 @@ on: pull_request: branches: [develop] workflow_dispatch: + +env: + DOCKER_NAME: ${{ vars.DOCKERHUB_USERNAME }}/${{ github.event.repository.name }}-frontend + jobs: + + build-prod-frontend-image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.DOCKER_NAME }} + + - name: Build Docker image + uses: docker/build-push-action@v5 + with: + context: ./frontend + file: ./frontend/Dockerfile.prod + push: false + + build-and-run-qa-tests: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/publish-and-test.yml b/.github/workflows/publish-and-test.yml index 650ea76082..96b5d9d2a7 100644 --- a/.github/workflows/publish-and-test.yml +++ b/.github/workflows/publish-and-test.yml @@ -194,6 +194,10 @@ jobs: [build-and-push-test-image-backend, build-and-push-test-image-frontend] runs-on: ubuntu-latest steps: + - name: Sleep for 2 minutes + run: sleep 2m + shell: bash + - name: Checkout OpenELIS-Global2 uses: actions/checkout@v4 with: diff --git a/.gitignore b/.gitignore index 18be1f7827..e9d1d78209 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ src/main/resources/adminPassword.txt /bin/ /.apt_generated/ */plugins/*.jar +Patient/* diff --git a/dev.docker-compose.yml b/dev.docker-compose.yml index ba9509cb44..3813849783 100644 --- a/dev.docker-compose.yml +++ b/dev.docker-compose.yml @@ -37,7 +37,7 @@ services: oe.openelis.org: container_name: openelisglobal-webapp - image: itechuw/openelis-global-2:develop + image: itechuw/openelis-global-2-dev:develop depends_on: - database - certs diff --git a/frontend/cypress/.eslintrc.json b/frontend/cypress/.eslintrc.json index d75b29358a..0f1b151455 100644 --- a/frontend/cypress/.eslintrc.json +++ b/frontend/cypress/.eslintrc.json @@ -1,5 +1,3 @@ { - "extends": [ - "plugin:cypress/recommended" - ] - } \ No newline at end of file + "extends": ["plugin:cypress/recommended"] +} diff --git a/frontend/cypress/e2e/orderEntity.cy.js b/frontend/cypress/e2e/orderEntity.cy.js index d25c462c9c..eb3bc308cd 100644 --- a/frontend/cypress/e2e/orderEntity.cy.js +++ b/frontend/cypress/e2e/orderEntity.cy.js @@ -53,7 +53,10 @@ describe("Order Entity", function () { orderEntityPage.clickNextButton(); }); - it("Should click generate Lab Order Number and store it in a fixture", function () { + it("Should do a validation check for labNo and then click generate Lab Order Number and store it in a fixture", function () { + cy.fixture("Order").then((order) => { + orderEntityPage.validateAcessionNumber(order.invalidLabNo); + }); orderEntityPage.generateLabOrderNumber(); cy.get("#labNo").then(($input) => { const generatedOrderNumber = $input.val(); diff --git a/frontend/cypress/e2e/patientEntry.cy.js b/frontend/cypress/e2e/patientEntry.cy.js index 8889e58efe..951c6f4499 100755 --- a/frontend/cypress/e2e/patientEntry.cy.js +++ b/frontend/cypress/e2e/patientEntry.cy.js @@ -119,6 +119,24 @@ describe("Patient Search", function () { cy.wait(200).reload(); }); + it("should search patient By Lab Number", function () { + cy.fixture("Patient").then((patient) => { + patientPage.searchPatientBylabNo(patient.labNo); + cy.intercept( + "GET", + `**/rest/patient-search-results?*labNumber=${patient.labNo}*`, + ).as("getPatientSearch"); + patientPage.clickSearchPatientButton(); + cy.wait("@getPatientSearch").then((interception) => { + const responseBody = interception.response.body; + console.log(responseBody); + expect(responseBody.patientSearchResults).to.be.an("array").that.is + .empty; + }); + }); + cy.wait(200).reload(); + }); + it("should search patient By PatientId", function () { cy.wait(1000); cy.fixture("Patient").then((patient) => { diff --git a/frontend/cypress/fixtures/Order.json b/frontend/cypress/fixtures/Order.json index 24626697d7..05213a9d4e 100644 --- a/frontend/cypress/fixtures/Order.json +++ b/frontend/cypress/fixtures/Order.json @@ -9,5 +9,6 @@ "firstName": "Optimus", "lastName": "Prime" }, - "labNo": "" + "labNo": "", + "invalidLabNo": "DEV0124000000000000" } diff --git a/frontend/cypress/fixtures/Patient.json b/frontend/cypress/fixtures/Patient.json index 4562e2696a..7a86bf897b 100644 --- a/frontend/cypress/fixtures/Patient.json +++ b/frontend/cypress/fixtures/Patient.json @@ -5,5 +5,6 @@ "subjectNumber": "001202782410", "nationalId": "UG-23SLHD7DBD", "DOB": "12/05/2001", - "gender": "Male" + "gender": "Male", + "labNo": "DEV01240000000000001" } diff --git a/frontend/cypress/pages/OrderEntityPage.js b/frontend/cypress/pages/OrderEntityPage.js index 642928b64f..2b87f86c0d 100644 --- a/frontend/cypress/pages/OrderEntityPage.js +++ b/frontend/cypress/pages/OrderEntityPage.js @@ -31,6 +31,18 @@ class OrderEntityPage { ).click(); } + validateAcessionNumber(order) { + cy.intercept("GET", `**/rest/SampleEntryAccessionNumberValidation**`).as( + "accessionNoValidation", + ); + cy.get("#labNo").type(order, { delay: 300 }); + + cy.wait("@accessionNoValidation").then((interception) => { + const responseBody = interception.response.body; + console.log(responseBody); + expect(responseBody.status).to.be.false; + }); + } enterSiteName(siteName) { cy.enterText("input#siteName", siteName); } diff --git a/frontend/cypress/pages/PatientEntryPage.js b/frontend/cypress/pages/PatientEntryPage.js index d9561f0a04..5b91aa4ced 100755 --- a/frontend/cypress/pages/PatientEntryPage.js +++ b/frontend/cypress/pages/PatientEntryPage.js @@ -8,6 +8,7 @@ class PatientEntryPage { personContactPrimaryPhone = "input#patientContact\\.person\\.primaryPhone"; personContactEmail = "input#patientContact\\.person\\.email"; patientIdSelector = "input#patientId"; + labNoSelector = "#labNumber"; city = "input#city"; primaryPhone = "input#primaryPhone"; dateOfBirth = "input#date-picker-default-id"; @@ -92,6 +93,10 @@ class PatientEntryPage { cy.enterText(this.patientIdSelector, PID); } + searchPatientBylabNo(labNo) { + cy.enterText(this.labNoSelector, labNo); + } + getPatientSearchResultsTable() { return cy.getElement( ".cds--data-table.cds--data-table--lg.cds--data-table--sort > tbody", diff --git a/frontend/src/App.js b/frontend/src/App.js index 7832218dfe..eff531cd88 100644 --- a/frontend/src/App.js +++ b/frontend/src/App.js @@ -40,7 +40,7 @@ import PrintBarcode from "./components/printBarcode/Index"; import NonConformIndex from "./components/nonconform/index"; import SampleBatchEntrySetup from "./components/batchOrderEntry/SampleBatchEntrySetup.js"; import AuditTrailReportIndex from "./components/reports/auditTrailReport/Index.js"; -import OrganizationAddEdit from "./components/admin/OrganizationManagement/OrganizationAddModify.js"; +import ReferredOutTests from "./components/resultPage/resultsReferredOut/ReferredOutTests.js"; export default function App() { let i18nConfig = { @@ -410,6 +410,12 @@ export default function App() { component={() => } role="Results" /> + } + role="Results" + /> + + + @@ -87,12 +95,18 @@ function Admin() { + + + + + + + + + @@ -184,6 +201,9 @@ function Admin() { + + + @@ -248,6 +268,9 @@ function Admin() { + + + ); } diff --git a/frontend/src/components/admin/OrganizationManagement/OrganizationAddModify.js b/frontend/src/components/admin/OrganizationManagement/OrganizationAddModify.js index f7652cd286..5c6dfb91e5 100644 --- a/frontend/src/components/admin/OrganizationManagement/OrganizationAddModify.js +++ b/frontend/src/components/admin/OrganizationManagement/OrganizationAddModify.js @@ -1,5 +1,4 @@ import React, { useContext, useState, useEffect, useRef } from "react"; -import { useLocation } from "react-router-dom"; import { Form, Heading, @@ -29,14 +28,17 @@ import { postToOpenElisServerFullResponse, postToOpenElisServerJsonResponse, } from "../../utils/Utils.js"; -import { NotificationContext } from "../../layout/Layout.js"; +import { + ConfigurationContext, + NotificationContext, +} from "../../layout/Layout.js"; import { AlertDialog, NotificationKinds, } from "../../common/CustomNotification.js"; -import { Field, Formik } from "formik"; import { FormattedMessage, injectIntl, useIntl } from "react-intl"; import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import AutoComplete from "../../common/AutoComplete.js"; let breadcrumbs = [ { label: "home.label", link: "/" }, @@ -50,6 +52,7 @@ let breadcrumbs = [ function OrganizationAddModify() { const { notificationVisible, setNotificationVisible, addNotification } = useContext(NotificationContext); + const { configurationProperties } = useContext(ConfigurationContext); const componentMounted = useRef(false); const intl = useIntl(); @@ -60,6 +63,10 @@ function OrganizationAddModify() { const [orgSelectedTypeOfActivity, setOrgSelectedTypeOfActivity] = useState( [], ); + const [parentOrgList, setParentOrgList] = useState([]); + const [parentOrgId, setParentOrgId] = useState(""); + const [parentOrg, setParentOrg] = useState({}); + const [parentOrgPost, setParentOrgPost] = useState({}); const [orgInfo, setOrgInfo] = useState({}); const [orgInfoPost, setOrgInfoPost] = useState({}); const [saveButton, setSaveButton] = useState(true); @@ -67,22 +74,12 @@ function OrganizationAddModify() { const [typeOfActivityShow, setTypeOfActivityShow] = useState([]); const [id, setId] = useState(null); - //const id = new URLSearchParams(useLocation().search).get("ID"); - useEffect(() => { const getIdFromUrl = () => { - // Get the hash part of the URL const hash = window.location.hash; - - // Check if the hash contains the query parameters if (hash.includes("?")) { - // Extract the query part from the hash const queryParams = hash.split("?")[1]; - - // Create a URLSearchParams object to easily access the parameters const urlParams = new URLSearchParams(queryParams); - - // Get the value of the 'ID' parameter const id = urlParams.get("ID"); return id; @@ -116,6 +113,21 @@ function OrganizationAddModify() { } }; + useEffect(() => { + getFromOpenElisServer( + `/rest/displayList/ACTIVE_ORG_LIST`, + handleParentOrgList, + ); + }, []); + + const handleParentOrgList = (res) => { + if (!res) { + setLoading(true); + } else { + setParentOrgList(res); + } + }; + useEffect(() => { if (typeOfActivity) { const newOrganizationsManagementList = typeOfActivity.orgTypes.map( @@ -142,8 +154,6 @@ function OrganizationAddModify() { }; const organizationsManagementIdInfoPost = { - departmentList: typeOfActivity.departmentList, - orgTypes: typeOfActivity.orgTypes, id: typeOfActivity.id, organizationName: typeOfActivity.organizationName, shortName: typeOfActivity.shortName, @@ -162,6 +172,7 @@ function OrganizationAddModify() { state: typeOfActivity.state, internetAddress: typeOfActivity.internetAddress, selectedTypes: typeOfActivity.selectedTypes, + organization: typeOfActivity.organization, }; setOrgInfo(organizationsManagementIdInfo); setOrgInfoPost(organizationsManagementIdInfoPost); @@ -237,16 +248,86 @@ function OrganizationAddModify() { function handleInternetAddressChange(e) { setSaveButton(false); + const value = e.target.value.trim(); + const urlPattern = + /^(https?:\/\/)?(www\.)?[\w-]+\.[a-z]{2,}(\.[a-z]{2,})?$/i; + + if (value && !urlPattern.test(value)) { + if (!notificationVisible) { + setNotificationVisible(true); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.organization.post.internetAddress", + }), + kind: NotificationKinds.info, + }); + } + } else { + setNotificationVisible(false); + } + setOrgInfoPost((prevOrgInfoPost) => ({ ...prevOrgInfoPost, - internetAddress: e.target.value, + internetAddress: value, })); setOrgInfo((prevOrgInfo) => ({ ...prevOrgInfo, - internetAddress: e.target.value, + internetAddress: value, })); } + function handleParentOrganizationName(e) { + setParentOrgPost({ + ...parentOrgPost, + parentOrganizationName: e.target.value, + }); + setSaveButton(false); + } + + function handleAutoCompleteParentOrganizationNames(parentOrgId) { + setParentOrgId(parentOrgId); + setSaveButton(false); + } + + const handleParentOrgPost = (res) => { + if (!res) { + setLoading(true); + } else { + setParentOrg(res); + } + }; + + useEffect(() => { + if (parentOrgId) { + getFromOpenElisServer( + `/rest/organization/${parentOrgId}`, + handleParentOrgPost, + ); + } + }, [parentOrgId]); + + useEffect(() => { + if (parentOrg) { + const parentOrgPost = { + id: parentOrg.id, + isActive: parentOrg.isActive, + lastupdated: parentOrg.lastupdated, + mlsSentinelLabFlag: parentOrg.mlsSentinelLabFlag, + organizationName: parentOrg.organizationName, + organizationTypes: parentOrg.organizationTypes, + shortName: parentOrg.shortName, + }; + setParentOrgPost(parentOrgPost); + setOrgInfoPost((prevOrgInfo) => ({ + ...prevOrgInfo, + organization: parentOrgPost, + })); + } + }, [parentOrg]); + function submitAddUpdatedOrgInfo() { setLoading(true); postToOpenElisServerJsonResponse( @@ -376,6 +457,7 @@ function OrganizationAddModify() { className="defalut" type="text" labelText="" + maxLength={15} placeholder={intl.formatMessage({ id: "organization.add.placeholder", })} @@ -428,7 +510,7 @@ function OrganizationAddModify() { type="text" labelText="" placeholder={intl.formatMessage({ - id: "organization.add.placeholder", + id: "organization.add.placeholder.internetAddress", })} // invalid={errors.order && touched.order} // invalidText={errors.order} @@ -441,6 +523,45 @@ function OrganizationAddModify() { /> + + + <> + : + + + + + {" "} + * + + } + style={{ width: "!important 100%" }} + suggestions={ + parentOrgList.length > 0 ? parentOrgList : [] + } + required + /> + + diff --git a/frontend/src/components/admin/OrganizationManagement/OrganizationManagement.js b/frontend/src/components/admin/OrganizationManagement/OrganizationManagement.js index 6ab8500426..65220eb260 100644 --- a/frontend/src/components/admin/OrganizationManagement/OrganizationManagement.js +++ b/frontend/src/components/admin/OrganizationManagement/OrganizationManagement.js @@ -1,6 +1,5 @@ import React, { useContext, useState, useEffect, useRef } from "react"; import { - Form, Heading, Button, Loading, @@ -35,6 +34,7 @@ import { import { FormattedMessage, injectIntl, useIntl } from "react-intl"; import PageBreadCrumb from "../../common/PageBreadCrumb.js"; import { ArrowLeft, ArrowRight } from "@carbon/icons-react"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; let breadcrumbs = [ { label: "home.label", link: "/" }, @@ -171,17 +171,6 @@ function OrganizationManagament() { useEffect(() => { if (organizationsManagmentList) { - const pagination = { - totalRecordCount: - organizationsManagmentList.modelMap.form.totalRecordCount, - fromRecordCount: - organizationsManagmentList.modelMap.form.fromRecordCount, - toRecordCount: organizationsManagmentList.modelMap.form.toRecordCount, - }; - setFromRecordCount(pagination.fromRecordCount); - setToRecordCount(pagination.toRecordCount); - setTotalRecordCount(pagination.totalRecordCount); - const newOrganizationsManagementList = organizationsManagmentList.modelMap.form.menuList.map((item) => { return { @@ -200,6 +189,13 @@ function OrganizationManagament() { const newOrganizationsManagementListArray = Object.values( newOrganizationsManagementList, ); + setFromRecordCount( + organizationsManagmentList.modelMap.form.fromRecordCount, + ); + setToRecordCount(organizationsManagmentList.modelMap.form.toRecordCount); + setTotalRecordCount( + organizationsManagmentList.modelMap.form.totalRecordCount, + ); setOrganizationsManagmentListShow(newOrganizationsManagementListArray); } }, [organizationsManagmentList]); @@ -259,6 +255,8 @@ function OrganizationManagament() { useEffect(() => { if (selectedRowIds.length === 0) { setDeactivateButton(true); + } else { + setDeactivateButton(false); } }, [selectedRowIds]); @@ -311,65 +309,22 @@ function OrganizationManagament() {
- - -
- {" "} - {" "} - -
-
-
-

- {fromRecordCount} -{" "} - {toRecordCount} {totalRecordCount}{" "} -

-
-
-
+ +
diff --git a/frontend/src/components/admin/ProviderMenu/ProviderMenu.js b/frontend/src/components/admin/ProviderMenu/ProviderMenu.js index 3f9ac8a85f..3244dd7879 100644 --- a/frontend/src/components/admin/ProviderMenu/ProviderMenu.js +++ b/frontend/src/components/admin/ProviderMenu/ProviderMenu.js @@ -1,6 +1,5 @@ import React, { useContext, useState, useEffect, useRef } from "react"; import { - Form, Heading, Button, Loading, @@ -37,10 +36,16 @@ import { } from "../../common/CustomNotification.js"; import { FormattedMessage, injectIntl, useIntl } from "react-intl"; import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import { ArrowLeft, ArrowRight } from "@carbon/icons-react"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; let breadcrumbs = [ { label: "home.label", link: "/" }, - // { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "provider.browse.title", + link: "/MasterListsPage#providerMenu", + }, ]; function ProviderMenu() { const { notificationVisible, setNotificationVisible, addNotification } = @@ -51,21 +56,23 @@ function ProviderMenu() { const componentMounted = useRef(false); const [page, setPage] = useState(1); - const [pageSize, setPageSize] = useState(5); + const [pageSize, setPageSize] = useState(10); const [modifyButton, setModifyButton] = useState(true); + const [deactivateButton, setDeactivateButton] = useState(true); const [selectedRowIds, setSelectedRowIds] = useState([]); - const [isEveryRowIsChecked, setIsEveryRowIsChecked] = useState(false); - const [rowsIsPartiallyChecked, setRowsIsPartiallyChecked] = useState(false); const [loading, setLoading] = useState(true); const [isSearching, setIsSearching] = useState(false); const [panelSearchTerm, setPanelSearchTerm] = useState(""); const [searchedProviderMenuList, setSearchedProviderMenuList] = useState([]); const [serachedProviderMenuListShow, setSearchedProviderMenuListShow] = useState([]); - // const [startingRecNo, setStartingRecNo] = useState(1); - const [providerMenuList, setProviderMenuList] = useState([]); + const [startingRecNo, setStartingRecNo] = useState(21); + const [providerMenuList, setProviderMenuList] = useState({}); const [providerMenuListShow, setProviderMenuListShow] = useState([]); - + const [fromRecordCount, setFromRecordCount] = useState(""); + const [toRecordCount, setToRecordCount] = useState(""); + const [totalRecordCount, setTotalRecordCount] = useState(""); + const [paging, setPaging] = useState(1); const [isAddModalOpen, setIsAddModalOpen] = useState(false); const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false); const [currentProvider, setCurrentProvider] = useState(null); @@ -81,43 +88,6 @@ function ProviderMenu() { { id: "no", value: "No" }, ]; - async function displayStatus(res) { - setNotificationVisible(true); - if (res.status == "201" || res.status == "200") { - addNotification({ - kind: NotificationKinds.success, - title: intl.formatMessage({ id: "notification.title" }), - message: intl.formatMessage({ id: "save.config.success.msg" }), - }); - } else { - addNotification({ - kind: NotificationKinds.error, - title: intl.formatMessage({ id: "notification.title" }), - message: intl.formatMessage({ id: "server.error.msg" }), - }); - } - reloadConfiguration(); - } - - function deleteDeactivateProvider(event) { - event.preventDefault(); - setLoading(true); - postToOpenElisServerFullResponse( - `/DeleteProvider?ID=${selectedRowIds.join(",")}&startingRecNo=1`, - serachedProviderMenuListShow || providerMenuListShow, // need to check against the form of restController [mentor] - setLoading(false), - setTimeout(() => { - window.location.reload(); - }, 1000), - ); - } - - const handlePageChange = ({ page, pageSize }) => { - setPage(page); - setPageSize(pageSize); - setSelectedRowIds([]); - }; - const handleMenuItems = (res) => { if (!res) { setLoading(true); @@ -129,12 +99,15 @@ function ProviderMenu() { useEffect(() => { componentMounted.current = true; setLoading(true); - getFromOpenElisServer(`/rest/ProviderMenu`, handleMenuItems); + getFromOpenElisServer( + `/rest/ProviderMenu?paging=${paging}&startingRecNo=${startingRecNo}`, + handleMenuItems, + ); return () => { componentMounted.current = false; setLoading(false); }; - }, []); + }, [paging, startingRecNo]); const handleSearchedProviderMenuList = (res) => { if (res) { @@ -144,14 +117,14 @@ function ProviderMenu() { useEffect(() => { getFromOpenElisServer( - `/rest/SearchProviderMenu?search=Y&startingRecNo=1&searchString=${panelSearchTerm}`, + `/rest/SearchProviderMenu?search=Y&startingRecNo=${startingRecNo}&searchString=${panelSearchTerm}`, handleSearchedProviderMenuList, ); }, [panelSearchTerm]); useEffect(() => { - if (providerMenuList) { - const newProviderMenuList = providerMenuList.map((item) => { + if (providerMenuList.providers) { + const newProviderMenuList = providerMenuList.providers.map((item) => { return { id: item.id, fhirUuid: item.fhirUuid, @@ -162,90 +135,109 @@ function ProviderMenu() { fax: item.person.fax, }; }); + setFromRecordCount(providerMenuList.fromRecordCount); + setToRecordCount(providerMenuList.toRecordCount); + setTotalRecordCount(providerMenuList.totalRecordCount); setProviderMenuListShow(newProviderMenuList); } }, [providerMenuList]); useEffect(() => { - if (searchedProviderMenuList) { - const newProviderMenuList = searchedProviderMenuList.map((item) => { - return { - id: item.id, - lastName: item.person.lastName, - firstName: item.person.firstName, - active: item.active, - telephone: item.person.telephone, - fax: item.person.fax, - }; - }); + if (searchedProviderMenuList.providers) { + const newProviderMenuList = searchedProviderMenuList.providers.map( + (item) => { + return { + id: item.id, + lastName: item.person.lastName, + firstName: item.person.firstName, + active: item.active, + telephone: item.person.telephone, + fax: item.person.fax, + }; + }, + ); setSearchedProviderMenuListShow(newProviderMenuList); } }, [searchedProviderMenuList]); useEffect(() => { - let currentPageIds; - if (searchedProviderMenuList) { - currentPageIds = searchedProviderMenuList - .slice((page - 1) * pageSize, page * pageSize) - .filter((row) => !row.disabled) - .map((row) => row.id); + if (selectedRowIds.length === 1) { + setModifyButton(false); } else { - currentPageIds = providerMenuListShow - .slice((page - 1) * pageSize, page * pageSize) - .filter((row) => !row.disabled) - .map((row) => row.id); + setModifyButton(true); } + }, [selectedRowIds]); - const currentPageSelectedIds = selectedRowIds.filter((id) => - currentPageIds.includes(id), - ); - - setIsEveryRowIsChecked( - currentPageSelectedIds.length === currentPageIds.length, - ); + useEffect(() => { + if (isSearching && panelSearchTerm === "") { + setIsSearching(false); + setPaging(1); + setStartingRecNo(1); + } + }, [isSearching, panelSearchTerm]); - setRowsIsPartiallyChecked( - currentPageSelectedIds.length > 0 && - currentPageSelectedIds.length < currentPageIds.length, - ); - }, [ - selectedRowIds, - page, - pageSize, - providerMenuListShow, - serachedProviderMenuListShow, - ]); + useEffect(() => { + if (selectedRowIds.length === 0) { + setDeactivateButton(true); + } else { + setDeactivateButton(false); + } + }, [selectedRowIds]); - const renderCell = (cell, row) => { - if (cell.info.header === "select") { - return ( - { - setModifyButton(false); - if (selectedRowIds.includes(row.id)) { - setSelectedRowIds(selectedRowIds.filter((id) => id !== row.id)); - } else { - setSelectedRowIds([...selectedRowIds, row.id]); - } - }} - /> - ); - } else if (cell.info.header === "active") { - return {cell.value.toString()}; + async function displayStatus(res) { + setNotificationVisible(true); + if (res.status == "201" || res.status == "200") { + addNotification({ + kind: NotificationKinds.success, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "save.config.success.msg" }), + }); } else { - return {cell.value}; + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); } + reloadConfiguration(); + } + + function deleteDeactivateProvider(event) { + event.preventDefault(); + setLoading(true); + postToOpenElisServerFullResponse( + `/DeleteProvider?ID=${selectedRowIds.join(",")}&${startingRecNo}=1`, + serachedProviderMenuListShow || providerMenuListShow, + setLoading(false), + setTimeout(() => { + window.location.reload(); + }, 1000), + ); + } + + const handlePageChange = ({ page, pageSize }) => { + setPage(page); + setPageSize(pageSize); + setSelectedRowIds([]); + }; + + const handleNextPage = () => { + setPaging((pager) => Math.max(pager, 2)); + setStartingRecNo(fromRecordCount); + }; + + const handlePreviousPage = () => { + setPaging((pager) => Math.max(pager - 1, 1)); + setStartingRecNo(Math.max(fromRecordCount, 1)); }; const handlePanelSearchChange = (event) => { setIsSearching(true); + setPaging(1); + setStartingRecNo(1); const query = event.target.value.toLowerCase(); setPanelSearchTerm(query); + setSelectedRowIds([]); }; const openAddModal = () => { @@ -310,7 +302,7 @@ function ProviderMenu() { active: isActive.id === "yes", }; postToOpenElisServerFullResponse( - "/rest/Provider/FhirUuid?fhirUuid="+currentProvider.fhirUuid, + "/rest/Provider/FhirUuid?fhirUuid=" + currentProvider.fhirUuid, JSON.stringify(updatedProvider), displayStatus, ); @@ -319,6 +311,32 @@ function ProviderMenu() { window.location.reload(); }; + const renderCell = (cell, row) => { + if (cell.info.header === "select") { + return ( + { + setDeactivateButton(false); + if (selectedRowIds.includes(row.id)) { + setSelectedRowIds(selectedRowIds.filter((id) => id !== row.id)); + } else { + setSelectedRowIds([...selectedRowIds, row.id]); + } + }} + /> + ); + } else if (cell.info.header === "active") { + return {cell.value.toString()}; + } else { + return {cell.value}; + } + }; + if (!loading) { return ( <> @@ -332,37 +350,31 @@ function ProviderMenu() { {notificationVisible === true ? : ""}
- +
-
-
-
- - {" "} - {" "} - - -
-
- +
+ +
- // !row.disabled && - // selectedRowIds.includes(row.id), - // ).length === pageSize - // } - checked={isEveryRowIsChecked} - // indeterminate={ - // selectedRowIds.length > 0 && - // selectedRowIds.length < - // serachedProviderMenuListShow - // .slice((page - 1) * pageSize, page * pageSize) - // .filter((row) => !row.disabled).length - // } - indeterminate={rowsIsPartiallyChecked} + checked={ + selectedRowIds.length === pageSize && + serachedProviderMenuListShow + .slice( + (page - 1) * pageSize, + page * pageSize, + ) + .filter( + (row) => + !row.disabled && + selectedRowIds.includes(row.id), + ).length === pageSize + } + indeterminate={ + selectedRowIds.length > 0 && + selectedRowIds.length < + serachedProviderMenuListShow + .slice( + (page - 1) * pageSize, + page * pageSize, + ) + .filter((row) => !row.disabled).length + } onSelect={() => { - setModifyButton(false); + setDeactivateButton(false); const currentPageIds = serachedProviderMenuListShow .slice( @@ -635,7 +651,7 @@ function ProviderMenu() { onChange={handlePageChange} page={page} pageSize={pageSize} - pageSizes={[5, 10, 15, 20, 25, 30]} + pageSizes={[10, 20]} totalItems={serachedProviderMenuListShow.length} forwardText={intl.formatMessage({ id: "pagination.forward", @@ -740,27 +756,31 @@ function ProviderMenu() { - // !row.disabled && - // selectedRowIds.includes(row.id), - // ).length === pageSize - // } - checked={isEveryRowIsChecked} - // indeterminate={ - // selectedRowIds.length > 0 && - // selectedRowIds.length < - // providerMenuListShow - // .slice((page - 1) * pageSize, page * pageSize) - // .filter((row) => !row.disabled).length - // } - indeterminate={rowsIsPartiallyChecked} + checked={ + selectedRowIds.length === pageSize && + providerMenuListShow + .slice( + (page - 1) * pageSize, + page * pageSize, + ) + .filter( + (row) => + !row.disabled && + selectedRowIds.includes(row.id), + ).length === pageSize + } + indeterminate={ + selectedRowIds.length > 0 && + selectedRowIds.length < + providerMenuListShow + .slice( + (page - 1) * pageSize, + page * pageSize, + ) + .filter((row) => !row.disabled).length + } onSelect={() => { - setModifyButton(false); + setDeactivateButton(false); const currentPageIds = providerMenuListShow .slice( (page - 1) * pageSize, @@ -835,7 +855,7 @@ function ProviderMenu() { onChange={handlePageChange} page={page} pageSize={pageSize} - pageSizes={[5, 10, 15, 20, 25, 30]} + pageSizes={[10, 20]} totalItems={providerMenuListShow.length} forwardText={intl.formatMessage({ id: "pagination.forward", diff --git a/frontend/src/components/admin/ResultReportingConfiguration/ResultReportingConfiguration.js b/frontend/src/components/admin/ResultReportingConfiguration/ResultReportingConfiguration.js new file mode 100644 index 0000000000..15458beecb --- /dev/null +++ b/frontend/src/components/admin/ResultReportingConfiguration/ResultReportingConfiguration.js @@ -0,0 +1,279 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Heading, + TextInput, + Button, + Grid, + Column, + Section, + RadioButton, + Loading, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerJsonResponse, +} from "../../utils/Utils"; +import { NotificationContext } from "../../layout/Layout"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "resultreporting.browse.title", + link: "/MasterListsPage#resultReportingConfiguration", + }, +]; + +function ResultReportingConfiguration() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + + const componentMounted = useRef(false); + + const intl = useIntl(); + + const [loading, setLoading] = useState(false); + const [reportsResp, setReportsResp] = useState({}); + const [reportsRespPost, setReportsRespPost] = useState({}); + const [saveButton, setSaveButton] = useState(true); + const [reportsShow, setReportsShow] = useState([]); + const [reportsShowMinList, setReportsShowMinList] = useState([]); + const [reportsShowHourList, setReportsShowHourList] = useState([]); + + const fetchPrograms = (programsList) => { + if (componentMounted.current) { + setReportsResp(programsList); + } + }; + + useEffect(() => { + if ( + reportsResp && + reportsResp.reports && + reportsResp.hourList && + reportsResp.minList + ) { + setReportsShow(reportsResp.reports); + setReportsShowHourList(reportsResp.hourList); + setReportsShowMinList(reportsResp.minList); + + const postObject = { + cancelMethod: reportsResp.cancelMethod, + cancelAction: reportsResp.cancelAction, + formMethod: reportsResp.formMethod, + formName: reportsResp.formName, + reports: reportsResp.reports, + hourList: reportsResp.hourList, + minList: reportsResp.minList, + }; + setReportsRespPost(postObject); + } + }, [reportsResp]); + + useEffect(() => { + setReportsRespPost((prevState) => ({ + ...prevState, + reports: reportsShow, + hourList: reportsShowHourList, + minList: reportsShowMinList, + })); + }, [reportsShow, reportsShowHourList, reportsShowMinList]); + + async function displayStatus(res) { + setNotificationVisible(true); + if (res) { + addNotification({ + kind: NotificationKinds.success, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "save.config.success.msg" }), + }); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + } + setLoading(false); + } + + function handleSubmit(event) { + event.preventDefault(); + setLoading(true); + postToOpenElisServerJsonResponse( + "/rest/ResultReportingConfiguration", + JSON.stringify(reportsRespPost), + (res) => { + displayStatus(res); + }, + ); + setTimeout(() => { + window.location.reload(); + }, 1000); + } + + const handleRadioChange = (index, value) => { + const updatedReports = reportsShow.map((report, i) => + i === index ? { ...report, enabled: value } : report, + ); + setReportsShow(updatedReports); + setSaveButton(false); + }; + + const handleUrlChange = (index, e) => { + const value = e.target.value.trim(); + const urlPattern = + /^(https?:\/\/)?(www\.)?[\w-]+\.[a-z]{2,}(\.[a-z]{2,})?$/i; + + if (value && !urlPattern.test(value)) { + if (!notificationVisible) { + setNotificationVisible(true); + addNotification({ + title: intl.formatMessage({ + id: "notification.title", + }), + message: intl.formatMessage({ + id: "notification.organization.post.internetAddress", + }), + kind: NotificationKinds.info, + }); + } + } else { + setNotificationVisible(false); + } + + const updatedReports = reportsShow.map((report, i) => + i === index ? { ...report, url: e.target.value } : report, + ); + setReportsShow(updatedReports); + setSaveButton(false); + }; + + useEffect(() => { + componentMounted.current = true; + getFromOpenElisServer("/rest/ResultReportingConfiguration", fetchPrograms); + + return () => { + componentMounted.current = false; + }; + }, []); + + return ( + <> + {/* {notificationVisible === true ? : ""} */} + {loading && } + {notificationVisible && } +
+ + + +
+ + + +
+
+
+
+ {reportsShow && + reportsShow.map((report, index) => ( +
+
+
+
+ + + +
+
+
+
+
+
+ handleRadioChange(index, "enable")} + /> + handleRadioChange(index, "disable")} + /> +
+
+
+ +
+
+ + + handleUrlChange(index, e)} + /> + + +
+
+ +
+
+
+ + {" "} + {report.backlogSize} + +
+
+
+
+
+ ))} + + + {" "} + + + +
+
+ + ); +} + +export default injectIntl(ResultReportingConfiguration); diff --git a/frontend/src/components/admin/analyzerTestName/AnalyzerTestName.js b/frontend/src/components/admin/analyzerTestName/AnalyzerTestName.js new file mode 100644 index 0000000000..97a02c115c --- /dev/null +++ b/frontend/src/components/admin/analyzerTestName/AnalyzerTestName.js @@ -0,0 +1,612 @@ +import React, { useContext, useState, useEffect, useRef } from "react"; +import { + Heading, + Loading, + Grid, + Column, + Section, + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableSelectRow, + TableSelectAll, + TableContainer, + Pagination, + Modal, + TextInput, + Dropdown, +} from "@carbon/react"; +import { + getFromOpenElisServer, + postToOpenElisServerFullResponse, +} from "../../utils/Utils.js"; +import { + ConfigurationContext, + NotificationContext, +} from "../../layout/Layout.js"; +import { + AlertDialog, + NotificationKinds, +} from "../../common/CustomNotification.js"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import ActionPaginationButtonType from "../../common/ActionPaginationButtonType.js"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "sidenav.label.admin.analyzerTest", + link: "/MasterListsPage#analyzerMenu", + }, +]; +function AnalyzerTestName() { + const { notificationVisible, setNotificationVisible, addNotification } = + useContext(NotificationContext); + const { reloadConfiguration } = useContext(ConfigurationContext); + + const intl = useIntl(); + + const componentMounted = useRef(false); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(10); + const [modifyButton, setModifyButton] = useState(true); + const [deactivateButton, setDeactivateButton] = useState(true); + const [selectedRowIds, setSelectedRowIds] = useState([]); + const [loading, setLoading] = useState(true); + const [startingRecNo, setStartingRecNo] = useState(21); + const [AnalyzerTestName, setAnalyzerTestName] = useState({}); + const [AnalyzerTestNameShow, setAnalyzerTestNameShow] = useState([]); + const [fromRecordCount, setFromRecordCount] = useState(""); + const [toRecordCount, setToRecordCount] = useState(""); + const [totalRecordCount, setTotalRecordCount] = useState(""); + const [paging, setPaging] = useState(1); + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false); + const [testName, setTestName] = useState(""); + const [analyzerList, setAnalyzerList] = useState([]); + const [testList, setTestList] = useState([]); + const [selectedAnalyzer, setSelectedAnalyzer] = useState(null); + const [selectedAnalyzerId, setSelectedAnalyzerId] = useState(null); + const [selectedTest, setSelectedTest] = useState(null); + const [selectedTestId, setSelectedTestId] = useState(null); + + const handleMenuItems = (res) => { + if (!res) { + setLoading(true); + } else { + setAnalyzerTestName(res); + } + }; + + useEffect(() => { + componentMounted.current = true; + setLoading(true); + getFromOpenElisServer("/rest/AnalyzerTestNameMenu", handleMenuItems); + return () => { + componentMounted.current = false; + setLoading(false); + }; + }, [paging, startingRecNo]); + + useEffect(() => { + if (AnalyzerTestName.menuList) { + const newAnalyzerTestName = AnalyzerTestName.menuList.map((item) => { + return { + id: item.uniqueId, + analyzerName: `${item.analyzerName} - ${item.analyzerTestName}`, + actualTestName: item.actualTestName, + }; + }); + setFromRecordCount(AnalyzerTestName.fromRecordCount); + setToRecordCount(AnalyzerTestName.menuList.length); + setTotalRecordCount(AnalyzerTestName.menuList.length); + setAnalyzerTestNameShow(newAnalyzerTestName); + } + }, [AnalyzerTestName]); + + const fetchDropdownData = async () => { + getFromOpenElisServer( + "/rest/AnalyzerTestName?ID=0&startingRecNo=1", + handleDropDown, + ); + }; + + function handleDropDown(response) { + if (response) { + setAnalyzerList(response.analyzerList || []); + setTestList(response.testList || []); + } + } + + useEffect(() => { + if (selectedRowIds.length === 1) { + setModifyButton(false); + } else { + setModifyButton(true); + } + }, [selectedRowIds]); + + useEffect(() => { + if (selectedRowIds.length === 0) { + setDeactivateButton(true); + } else { + setDeactivateButton(false); + } + }, [selectedRowIds]); + + async function displayStatus(res) { + setNotificationVisible(true); + if (res.status == "201" || res.status == "200") { + addNotification({ + kind: NotificationKinds.success, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "save.config.success.msg" }), + }); + } else { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ id: "server.error.msg" }), + }); + } + reloadConfiguration(); + } + + function deleteDeactivateAnalyzer(event) { + event.preventDefault(); + setLoading(true); + const selectedIds = { selectedIDs: selectedRowIds }; + postToOpenElisServerFullResponse( + `/rest/DeleteAnalyzerTestName?ID=${selectedRowIds.join(",")}&${startingRecNo}=1`, + JSON.stringify(selectedIds), + setLoading(false), + setTimeout(() => { + window.location.reload(); + }, 1000), + ); + } + + const handlePageChange = ({ page, pageSize }) => { + setPage(page); + setPageSize(pageSize); + setSelectedRowIds([]); + }; + + const handleNextPage = () => { + setPaging((pager) => Math.max(pager, 2)); + setStartingRecNo(fromRecordCount); + }; + + const handlePreviousPage = () => { + setPaging((pager) => Math.max(pager - 1, 1)); + setStartingRecNo(Math.max(fromRecordCount, 1)); + }; + + const openAddModal = () => { + setTestName(""); + setSelectedAnalyzer(null); + setSelectedAnalyzerId(null); + setSelectedTest(null); + setSelectedTestId(null); + fetchDropdownData(); + setIsAddModalOpen(true); + }; + + const closeAddModal = () => { + setIsAddModalOpen(false); + }; + + const openUpdateModal = (AnalyzerId) => { + fetchDropdownData(); + setIsUpdateModalOpen(true); + }; + + const closeUpdateModal = () => { + setIsUpdateModalOpen(false); + }; + const checkIfCombinationExists = () => { + return AnalyzerTestNameShow.some( + (item) => item.analyzerName === `${selectedAnalyzer.name} - ${testName}`, + ); + }; + + const handleAddAnalyzer = () => { + if (checkIfCombinationExists()) { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ + id: "analyzer.combinationName.notification", + }), + }); + setNotificationVisible(true); + return; + } + + const newAnalyzer = { + analyzerId: selectedAnalyzerId, + analyzerTestName: testName, + testId: selectedTestId, + }; + + postToOpenElisServerFullResponse( + "/rest/AnalyzerTestName", + JSON.stringify(newAnalyzer), + displayStatus, + ); + + closeAddModal(); + window.location.reload(); + }; + + const handleUpdateAnalyzer = () => { + if (checkIfCombinationExists()) { + addNotification({ + kind: NotificationKinds.error, + title: intl.formatMessage({ id: "notification.title" }), + message: intl.formatMessage({ + id: "analyzer.combinationName.notification", + }), + }); + setNotificationVisible(true); + return; + } + const newAnalyzer = { + analyzerId: selectedAnalyzerId, + analyzerTestName: testName, + testId: selectedTestId, + }; + + postToOpenElisServerFullResponse( + "/rest/AnalyzerTestName", + JSON.stringify(newAnalyzer), + displayStatus, + ); + + closeUpdateModal(); + + window.location.reload(); + }; + + const renderCell = (cell, row) => { + if (cell.info.header === "select") { + return ( + { + setDeactivateButton(false); + if (selectedRowIds.includes(row.id)) { + setSelectedRowIds(selectedRowIds.filter((id) => id !== row.id)); + } else { + setSelectedRowIds([...selectedRowIds, row.id]); + } + }} + /> + ); + } else if (cell.info.header === "active") { + return {cell.value.toString()}; + } else { + return {cell.value}; + } + }; + + if (!loading) { + return ( + <> + + + ); + } + + return ( + <> + {notificationVisible === true ? : ""} +
+ + + +
+ + + +
+
+
+
+ +
+ + (item ? item.name : "")} + selectedItem={selectedAnalyzer} + onChange={({ selectedItem }) => { + setSelectedAnalyzer(selectedItem); + setSelectedAnalyzerId(selectedItem ? selectedItem.id : null); + }} + /> +
+ setTestName(e.target.value)} + required + /> +
+ + (item ? item.name : "")} + selectedItem={selectedTest} + onChange={({ selectedItem }) => { + setSelectedTest(selectedItem); + setSelectedTestId(selectedItem ? selectedItem.id : null); + }} + /> +
+ + + (item ? item.name : "")} + selectedItem={selectedAnalyzer} + onChange={({ selectedItem }) => { + setSelectedAnalyzer(selectedItem); + setSelectedAnalyzerId(selectedItem ? selectedItem.id : null); + }} + /> +
+ + setTestName(e.target.value)} + required + /> +
+ + (item ? item.name : "")} + selectedItem={selectedTest} + onChange={({ selectedItem }) => { + setSelectedTest(selectedItem); + setSelectedTestId(selectedItem ? selectedItem.id : null); + }} + /> +
+ +
+ <> + + + + {({ + rows, + headers, + getHeaderProps, + getTableProps, + getSelectionProps, + }) => ( + + + + + + !row.disabled && + selectedRowIds.includes(row.id), + ).length === pageSize + } + indeterminate={ + selectedRowIds.length > 0 && + selectedRowIds.length < + AnalyzerTestNameShow.slice( + (page - 1) * pageSize, + page * pageSize, + ).filter((row) => !row.disabled).length + } + onSelect={() => { + setDeactivateButton(false); + const currentPageIds = + AnalyzerTestNameShow.slice( + (page - 1) * pageSize, + page * pageSize, + ) + .filter((row) => !row.disabled) + .map((row) => row.id); + if ( + selectedRowIds.length === pageSize && + currentPageIds.every((id) => + selectedRowIds.includes(id), + ) + ) { + setSelectedRowIds([]); + } else { + setSelectedRowIds( + currentPageIds.filter( + (id) => !selectedRowIds.includes(id), + ), + ); + } + }} + /> + {headers.map( + (header) => + header.key !== "select" && ( + + {header.header} + + ), + )} + + + + <> + {rows.map((row) => ( + { + const id = row.id; + const isSelected = + selectedRowIds.includes(id); + if (isSelected) { + setSelectedRowIds( + selectedRowIds.filter( + (selectedId) => selectedId !== id, + ), + ); + } else { + setSelectedRowIds([...selectedRowIds, id]); + } + }} + > + {row.cells.map((cell) => renderCell(cell, row))} + + ))} + + +
+
+ )} +
+ + intl.formatMessage( + { id: "pagination.item-range" }, + { min: min, max: max, total: total }, + ) + } + itemsPerPageText={intl.formatMessage({ + id: "pagination.items-per-page", + })} + itemText={(min, max) => + intl.formatMessage( + { id: "pagination.item" }, + { min: min, max: max }, + ) + } + pageNumberText={intl.formatMessage({ + id: "pagination.page-number", + })} + pageRangeText={(_current, total) => + intl.formatMessage( + { id: "pagination.page-range" }, + { total: total }, + ) + } + pageText={(page, pagesUnknown) => + intl.formatMessage( + { id: "pagination.page" }, + { page: pagesUnknown ? "" : page }, + ) + } + /> +
+
+ +
+
+ + ); +} + +export default injectIntl(AnalyzerTestName); diff --git a/frontend/src/components/admin/calculatedValue/CalculatedValueForm.tsx b/frontend/src/components/admin/calculatedValue/CalculatedValueForm.tsx index ed50be7b0d..4642488632 100644 --- a/frontend/src/components/admin/calculatedValue/CalculatedValueForm.tsx +++ b/frontend/src/components/admin/calculatedValue/CalculatedValueForm.tsx @@ -107,31 +107,59 @@ const CalculatedValue: React.FC = () => { const loadCalculationList = (calculations) => { if (componentMounted.current) { // console.log(JSON.stringify(reflexRuleList)) + const sampleList = []; if (calculations.length > 0) { setCalculationList(calculations); calculations.forEach((calculation, index) => { if (calculation.sampleId) { - getFromOpenElisServer( - "/rest/test-display-beans?sampleType=" + calculation.sampleId, - (resp) => fetchTests(resp, "FINAL_RESULT", index, 0), - ); + sampleList.push(calculation.sampleId); } calculation.operations.forEach((operation, opeartionIdex) => { if (operation.sampleId) { - getFromOpenElisServer( - "/rest/test-display-beans?sampleType=" + operation.sampleId, - (resp) => fetchTests(resp, "TEST_RESULT", index, opeartionIdex), - ); + sampleList.push(operation.sampleId); } }); }); + getFromOpenElisServer( + "/rest/test-display-beans-map?samplesTypes=" + sampleList.join(","), + (resp) => buildSampleTests(resp, calculations), + ); } setLoading(false); } }; + const buildSampleTests = (sampleTestsMap, calculations) => { + if (calculations.length > 0) { + setCalculationList(calculations); + + calculations.forEach((calculation, index) => { + if (calculation.sampleId) { + sampleList.push(calculation.sampleId); + fetchTests( + sampleTestsMap[calculation.sampleId], + "FINAL_RESULT", + index, + 0, + ); + } + + calculation.operations.forEach((operation, opeartionIdex) => { + if (operation.sampleId) { + fetchTests( + sampleTestsMap[operation.sampleId], + "TEST_RESULT", + index, + opeartionIdex, + ); + } + }); + }); + } + }; + const loadMathFunctions = (functions) => { setMathFunctions(functions); }; @@ -167,9 +195,6 @@ const CalculatedValue: React.FC = () => { }; const handleRuleRemove = (index, id) => { - const list = [...calculationList]; - list.splice(index, 1); - setCalculationList(list); if (id) { postToOpenElisServer( "/rest/deactivate-test-calculation/" + id, @@ -187,6 +212,7 @@ const CalculatedValue: React.FC = () => { title: intl.formatMessage({ id: "notification.title" }), message: intl.formatMessage({ id: "delete.success.msg" }), }); + window.location.reload() } else { addNotification({ kind: NotificationKinds.error, diff --git a/frontend/src/components/admin/pluginFile/PluginFile.js b/frontend/src/components/admin/pluginFile/PluginFile.js new file mode 100644 index 0000000000..7464f2bf4d --- /dev/null +++ b/frontend/src/components/admin/pluginFile/PluginFile.js @@ -0,0 +1,97 @@ +import React, { useState, useEffect } from "react"; +import { + DataTable, + Table, + TableHead, + TableRow, + TableBody, + TableHeader, + TableCell, + TableContainer, + Loading, +} from "@carbon/react"; +import { getFromOpenElisServer } from "../../utils/Utils.js"; +import PageBreadCrumb from "../../common/PageBreadCrumb.js"; +import { FormattedMessage } from "react-intl"; + +let breadcrumbs = [ + { label: "home.label", link: "/" }, + { label: "breadcrums.admin.managment", link: "/MasterListsPage" }, + { + label: "sidenav.label.admin.pluginFile", + link: "/MasterListsPage#PluginFile", + }, +]; + +function PluginList() { + const [plugins, setPlugins] = useState([]); + const [loading, setLoading] = useState(true); + + const handlePlugins = (res) => { + if (res) { + setPlugins(res.pluginList || []); + } + setLoading(false); + }; + + useEffect(() => { + getFromOpenElisServer("/rest/ListPlugins", handlePlugins); + }, []); + + const headers = [{ key: "pluginName", header: "Plugin Name" }]; + + const rows = plugins.map((plugin, index) => ({ + id: String(index), + pluginName: plugin, + })); + + if (loading) { + return ; + } + + return ( +
+ + +
+ + {plugins.length === 0 ? ( +

+ +

+ ) : ( + + {({ rows, headers, getHeaderProps, getTableProps }) => ( + + + + {headers.map((header) => ( + + {header.header} + + ))} + + + + {rows.map((row) => ( + + {row.cells.map((cell) => ( + {cell.value} + ))} + + ))} + +
+ )} +
+ )} +
+
+
+ ); +} + +export default PluginList; diff --git a/frontend/src/components/admin/reflexTests/ReflexRuleForm.js b/frontend/src/components/admin/reflexTests/ReflexRuleForm.js index 8d195ea7fb..b0f4e66116 100644 --- a/frontend/src/components/admin/reflexTests/ReflexRuleForm.js +++ b/frontend/src/components/admin/reflexTests/ReflexRuleForm.js @@ -110,20 +110,41 @@ function ReflexRule() { }, [ruleList]); const loadDefaultTestResultList = () => { + var sampleList = []; ruleList.forEach(function (rule, index) { if (rule.conditions) { rule.conditions.forEach(function (condition, conditionIndex) { if (condition.sampleId) { - getFromOpenElisServer( - "/rest/test-display-beans?sampleType=" + condition.sampleId, - (resp) => - fetchDeafultTests( - resp, - index, - conditionIndex, - FIELD.conditions, - condition, - ), + sampleList.push(condition.sampleId); + } + }); + } + if (rule.actions) { + rule.actions.forEach(function (action, actionIndex) { + if (action.sampleId) { + sampleList.push(action.sampleId); + } + }); + } + }); + + getFromOpenElisServer( + "/rest/test-display-beans-map?samplesTypes=" + sampleList.join(","), + (resp) => buildSampleTests(resp), + ); + }; + + const buildSampleTests = (sampleTestsMap) => { + ruleList.forEach(function (rule, index) { + if (rule.conditions) { + rule.conditions.forEach(function (condition, conditionIndex) { + if (condition.sampleId) { + fetchDeafultTests( + sampleTestsMap[condition.sampleId], + index, + conditionIndex, + FIELD.conditions, + condition, ); } }); @@ -131,16 +152,12 @@ function ReflexRule() { if (rule.actions) { rule.actions.forEach(function (action, actionIndex) { if (action.sampleId) { - getFromOpenElisServer( - "/rest/test-display-beans?sampleType=" + action.sampleId, - (resp) => - fetchDeafultTests( - resp, - index, - actionIndex, - FIELD.actions, - null, - ), + fetchDeafultTests( + sampleTestsMap[action.sampleId], + index, + actionIndex, + FIELD.actions, + null, ); } }); @@ -273,9 +290,6 @@ function ReflexRule() { }; const handleRuleRemove = (index, id) => { - const list = [...ruleList]; - list.splice(index, 1); - setRuleList(list); if (id) { postToOpenElisServer( "/rest/deactivate-reflexrule/" + id, @@ -291,13 +305,14 @@ function ReflexRule() { addNotification({ kind: NotificationKinds.success, title: intl.formatMessage({ id: "notification.title" }), - message: intl.formatMessage({ id: "success.deleted.msg" }), + message: intl.formatMessage({ id: "delete.success.msg" }), }); + window.location.reload() } else { addNotification({ kind: NotificationKinds.error, title: intl.formatMessage({ id: "notification.title" }), - message: intl.formatMessage({ id: "error.deleted.msg" }), + message: intl.formatMessage({ id: "delete.error.msg" }), }); } }; diff --git a/frontend/src/components/common/ActionPaginationButtonType.js b/frontend/src/components/common/ActionPaginationButtonType.js new file mode 100644 index 0000000000..9ee11d3f01 --- /dev/null +++ b/frontend/src/components/common/ActionPaginationButtonType.js @@ -0,0 +1,140 @@ +import React from "react"; +import PropTypes from "prop-types"; +import { Button, Grid, Column, Section } from "@carbon/react"; +import { FormattedMessage, injectIntl, useIntl } from "react-intl"; +import { ArrowLeft, ArrowRight } from "@carbon/icons-react"; + +const ActionPaginationButtonType = ({ + selectedRowIds, + modifyButton, + deactivateButton, + deleteDeactivate, + openUpdateModal, + openAddModal, + handlePreviousPage, + handleNextPage, + fromRecordCount, + toRecordCount, + totalRecordCount, + addButtonRedirectLink, + modifyButtonRedirectLink, + id, + type, +}) => { + const intl = useIntl(); + + return ( + + +
+
+ {type === "type1" ? ( + <> + {" "} + {" "} + + + ) : ( + <> + {" "} + {" "} + + + )} +
+
+

+ {fromRecordCount} -{" "} + {toRecordCount} {totalRecordCount}{" "} +

+
+
+
+
+ ); +}; + +ActionPaginationButtonType.propTypes = { + selectedRowIds: PropTypes.array.isRequired, + modifyButton: PropTypes.bool.isRequired, + deactivateButton: PropTypes.bool.isRequired, + deleteDeactivate: PropTypes.func.isRequired, + handlePreviousPage: PropTypes.func.isRequired, + handleNextPage: PropTypes.func.isRequired, + fromRecordCount: PropTypes.string.isRequired, + toRecordCount: PropTypes.string.isRequired, + totalRecordCount: PropTypes.string.isRequired, + addButtonRedirectLink: PropTypes.string, + modifyButtonRedirectLink: PropTypes.string, + openUpdateModal: PropTypes.func, + openAddModal: PropTypes.func, + id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + type: PropTypes.oneOf(["type1", "type2"]).isRequired, +}; + +export default injectIntl(ActionPaginationButtonType); diff --git a/frontend/src/components/common/CustomDatePicker.js b/frontend/src/components/common/CustomDatePicker.js index 220a68c554..9ac12acd93 100644 --- a/frontend/src/components/common/CustomDatePicker.js +++ b/frontend/src/components/common/CustomDatePicker.js @@ -75,6 +75,7 @@ const CustomDatePicker = (props) => { labelText={props.labelText} invalid={props.invalid} invalidText={props.invalidText} + disabled={props.disabled} /> diff --git a/frontend/src/components/formModel/innitialValues/ReferredOutTestsFormValues.js b/frontend/src/components/formModel/innitialValues/ReferredOutTestsFormValues.js new file mode 100644 index 0000000000..94618822ab --- /dev/null +++ b/frontend/src/components/formModel/innitialValues/ReferredOutTestsFormValues.js @@ -0,0 +1,11 @@ +const ReferredOutTestsFormValues = { + labNumberInput: "", + selectedPatientId: "", + startDate: "", + endDate: "", + dateType: "", + dateOfBirth: "", + searchTypeValues: ["TEST_AND_DATES", "LAB_NUMBER", "PATIENT"], +}; + +export default ReferredOutTestsFormValues; diff --git a/frontend/src/components/immunohistochemistry/ImmunohistochemistryCaseView.js b/frontend/src/components/immunohistochemistry/ImmunohistochemistryCaseView.js index 48edcce17b..a9de3a6429 100644 --- a/frontend/src/components/immunohistochemistry/ImmunohistochemistryCaseView.js +++ b/frontend/src/components/immunohistochemistry/ImmunohistochemistryCaseView.js @@ -947,7 +947,11 @@ function ImmunohistochemistryCaseView() { - +
diff --git a/frontend/src/components/patient/resultsViewer/grouped-timeline/grouped-timeline.styles.scss b/frontend/src/components/patient/resultsViewer/grouped-timeline/grouped-timeline.styles.scss index 87b7bb2c47..6194ab82c8 100644 --- a/frontend/src/components/patient/resultsViewer/grouped-timeline/grouped-timeline.styles.scss +++ b/frontend/src/components/patient/resultsViewer/grouped-timeline/grouped-timeline.styles.scss @@ -80,7 +80,7 @@ overflow-x: scroll; width: 100%; background-color: white; - scrollbar-width: none; + scrollbar-width: auto; // &::-webkit-scrollbar { // // needed for Chrome, Edge, Opera, Safari // display: none; diff --git a/frontend/src/components/reports/Routine.js b/frontend/src/components/reports/Routine.js index 6fe2e7980d..d9ac90221c 100644 --- a/frontend/src/components/reports/Routine.js +++ b/frontend/src/components/reports/Routine.js @@ -130,7 +130,7 @@ export const RoutineReportsMenu = { icon: IbmWatsonNaturalLanguageUnderstanding, SideNavMenuItem: [ { - link: "/RoutineReport?type=patient&report=CISampleRoutineExport", + link: "/RoutineReport?type=routine&report=CISampleRoutineExport", label: , }, ], diff --git a/frontend/src/components/reports/common/PatientStatusReport.js b/frontend/src/components/reports/common/PatientStatusReport.js index 2d259c6d89..0327b5f6ba 100644 --- a/frontend/src/components/reports/common/PatientStatusReport.js +++ b/frontend/src/components/reports/common/PatientStatusReport.js @@ -64,7 +64,7 @@ function PatientStatusReport(props) { const handleReportPrint = () => { let barcodesPdf = config.serverBaseUrl + - `/ReportPrint?report=${props.report}&type=patient&accessionDirect=${reportFormValues.form}&highAccessionDirect=${reportFormValues.to}&dateOfBirthSearchValue=&selPatient=${reportFormValues.selectedPatientId}&referringSiteId=${reportFormValues.referringSiteId}&referringSiteDepartmentId=${reportFormValues.referringSiteName}&onlyResults=${result}&_onlyResults=${checkbox}&dateType=${items}&lowerDateRange=${reportFormValues.startDate}&upperDateRange=${reportFormValues.endDate}`; + `/ReportPrint?report=${props.report}&type=patient&accessionDirect=${reportFormValues.form}&highAccessionDirect=${reportFormValues.to}&dateOfBirthSearchValue=&selPatient=${reportFormValues.selectedPatientId}&referringSiteId=${reportFormValues.referringSiteId}&referringSiteDepartmentId=${reportFormValues.referringSiteDepartmentId ? reportFormValues.referringSiteDepartmentId : ""}&onlyResults=${result}&_onlyResults=${checkbox}&dateType=${items}&lowerDateRange=${reportFormValues.startDate}&upperDateRange=${reportFormValues.endDate}`; window.open(barcodesPdf); }; @@ -343,22 +343,16 @@ function PatientStatusReport(props) { - - - - -
-
- -
- -
-
-
- - + + +
+
+ +
+ +
+
+
{ props.report === "activityReportByTestSection" ) { baseParams = `type=indicator&report=${props.report}&selectList.selection=${reportFormValues.value}`; + } else if (props.report === "CISampleRoutineExport") { + baseParams = `report=${props.report}&type=routine`; } else { baseParams = `report=${props.report}&type=patient`; } const baseUrl = `${config.serverBaseUrl}/ReportPrint`; + const url = `${baseUrl}?${baseParams}&upperDateRange=${reportFormValues.endDate}&lowerDateRange=${reportFormValues.startDate}`; window.open(url, "_blank"); diff --git a/frontend/src/components/reports/routine/Index.js b/frontend/src/components/reports/routine/Index.js index 8e1c06852d..b0c25e970d 100644 --- a/frontend/src/components/reports/routine/Index.js +++ b/frontend/src/components/reports/routine/Index.js @@ -38,7 +38,7 @@ export const RoutineReports = (props) => { /> )} - {type === "patient" && report === "CISampleRoutineExport" && ( + {type === "routine" && report === "CISampleRoutineExport" && ( { /> )} + {type === "patient" && report === "ExportWHONETReportByDate" && ( + + )} + {type === "routine" && report === "auditTrail" && ( )} diff --git a/frontend/src/components/resultPage/SearchResultForm.js b/frontend/src/components/resultPage/SearchResultForm.js index d41e06a775..ab9ae9287c 100644 --- a/frontend/src/components/resultPage/SearchResultForm.js +++ b/frontend/src/components/resultPage/SearchResultForm.js @@ -28,6 +28,7 @@ import SearchResultFormValues from "../formModel/innitialValues/SearchResultForm import { AlertDialog, NotificationKinds } from "../common/CustomNotification"; import { NotificationContext } from "../layout/Layout"; import SearchPatientForm from "../patient/SearchPatientForm"; +import ReferredOutTests from "./resultsReferredOut/ReferredOutTests"; import { ConfigurationContext } from "../layout/Layout"; import config from "../../config.json"; import CustomDatePicker from "../common/CustomDatePicker"; @@ -57,6 +58,7 @@ function ResultSearchPage() { searchBy={searchBy} results={resultForm} setResultForm={setResultForm} + refreshOnSubmit={true} /> ); @@ -695,6 +697,8 @@ export function SearchResultForm(props) { )} + {searchBy.type === "ReferredOutTests" && } + <> {pagination && ( @@ -743,6 +747,7 @@ export function SearchResults(props) { const [rejectedItems, setRejectedItems] = useState({}); const [validationState, setValidationState] = useState({}); const saveStatus = ""; + const [referTest, setReferTest] = useState({}); const componentMounted = useRef(false); @@ -1183,7 +1188,7 @@ export function SearchResults(props) { name={"testResult[" + data.id + "].testMethod"} labelText={intl.formatMessage({ id: "referral.label.testmethod" })} onChange={(e) => handleChange(e, data.id)} - value={data.method} + value={data.testMethod} > {methods.map((method, method_index) => ( @@ -1195,13 +1200,29 @@ export function SearchResults(props) { ))} + + + { + e.target.value = e.target.checked; + handleChange(e, data.id); + }} + /> + handleChange(e, data.id)} + value={data?.referralItem?.referredInstituteId} + disabled={!referTest[data.id]} > {/* {...updateShadowResult(e, this, param.rowId)} */} @@ -1233,12 +1258,14 @@ export function SearchResults(props) { + )} + + + +
+ +
+
+ +

+
+ + item.value === dateType) + ?.text || "" + } + initialSelectedItem={dateTypeList.find( + (item) => item.value === dateType, + )} + items={dateTypeList} + itemToString={(item) => (item ? item.text : "")} + onChange={(item) => { + setSearchType( + referredOutTestsFormValues.searchTypeValues[0], + ); + setDateType(item.selectedItem.value); + setSearchByUnit(false); + }} + /> + + + + + +

+
+ + + { + handleDatePickerChangeDate("startDate", date); + }} + /> + + + { + handleDatePickerChangeDate("endDate", date); + }} + /> + + +

+
+ + + (item ? item.value : "")} + onChange={(changes) => { + setTestUnits({ + ...testUnits, + testUnits: changes.selectedItems, + }); + setSearchType( + referredOutTestsFormValues.searchTypeValues[0], + ); + setSearchByUnit(false); + }} + selectionFeedback="top-after-reopen" + /> + + + + {testUnits.testUnits && + testUnits.testUnits.map((test, index) => ( + { + var info = { ...testUnits }; + info["testUnits"].splice(index, 1); + setTestUnits(info); + }} + > + {test.value} + + ))} + + +

+
+ + (item ? item.value : "")} + onChange={(changes) => { + setTestNames({ + ...testNames, + testNames: changes.selectedItems, + }); + setSearchType( + referredOutTestsFormValues.searchTypeValues[0], + ); + setSearchByUnit(false); + }} + selectionFeedback="top-after-reopen" + /> + + + + {testNames.testNames && + testNames.testNames.map((test, index) => ( + { + var info = { ...testNames }; + info["testNames"].splice(index, 1); + setTestNames(info); + }} + > + {test.value} + + ))} + + +

+
+ + + + +
+
+ + +
+ +
+
+ +

+
+ + + + {({ field }) => ( + { + setFieldValue(field.name, rawValue); + setSearchType( + referredOutTestsFormValues.searchTypeValues[1], + ); + handleLabNumberSearch(e); + }} + /> + )} + + + +

+
+ + + + +
+
+ + )} + +
+ + + + : + {" "} + + + {" "} + + + {responseDataShow && ( + + )}{" "} + + + + + +
+ + +
+ {responseDataShow && ( + + {({ + rows, + headers, + getHeaderProps, + getTableProps, + getSelectionProps, + }) => ( + + + + + + !row.disabled && + selectedRowIds.includes(index), + ).length === pageSize + } + indeterminate={ + selectedRowIds.length > 0 && + selectedRowIds.length < + responseDataShow + .slice((page - 1) * pageSize, page * pageSize) + .filter((row) => !row.disabled).length + } + onSelect={() => { + const currentPageIds = responseDataShow + .slice((page - 1) * pageSize, page * pageSize) + .filter((row) => !row.disabled) + .map((row, index) => index); + if ( + selectedRowIds.length === pageSize && + currentPageIds.every((index) => + selectedRowIds.includes(index), + ) + ) { + setSelectedRowIds([]); + } else { + setSelectedRowIds( + currentPageIds.filter( + (index) => !selectedRowIds.includes(index), + ), + ); + } + }} + /> + {headers.map( + (header) => + header.key !== "select" && ( + + {header.header} + + ), + )} + + + + <> + {rows.map((row, rowIndex) => ( + { + const index = responseDataShow.findIndex( + (item) => item.id === row.id, + ); + const isSelected = + selectedRowIds.includes(index); + if (isSelected) { + setSelectedRowIds( + selectedRowIds.filter( + (selectedId) => selectedId !== index, + ), + ); + } else { + setSelectedRowIds([...selectedRowIds, index]); + } + }} + > + {row.cells.map((cell) => + renderCell(cell, row, rowIndex), + )} + + ))} + + +
+
+ )} +
+ )} + {responseDataShow && ( + + intl.formatMessage( + { id: "pagination.item-range" }, + { min: min, max: max, total: total }, + ) + } + itemsPerPageText={intl.formatMessage({ + id: "pagination.items-per-page", + })} + itemText={(min, max) => + intl.formatMessage( + { id: "pagination.item" }, + { min: min, max: max }, + ) + } + pageNumberText={intl.formatMessage({ + id: "pagination.page-number", + })} + pageRangeText={(_current, total) => + intl.formatMessage( + { id: "pagination.page-range" }, + { total: total }, + ) + } + pageText={(page, pagesUnknown) => + intl.formatMessage( + { id: "pagination.page" }, + { page: pagesUnknown ? "" : page }, + ) + } + /> + )} +
+
+
+
+ + ); +} + +export default injectIntl(ReferredOutTests); diff --git a/frontend/src/languages/en.json b/frontend/src/languages/en.json index 042ea54f84..61f548691e 100644 --- a/frontend/src/languages/en.json +++ b/frontend/src/languages/en.json @@ -37,6 +37,7 @@ "login.msg.username.missing": "A username is required", "login.msg.password.missing": "A password is required", "login.notice.message": "Notice: Access to this service is for authorized personnel only. If you do not have the expressed authorization of the administrator, you must exit now. This organization prohibits unauthorized access, disclosure, duplication, modification, diversion, destruction, loss, misuse, or theft of its information.", + "message.noPluginFound": "No plugins Found", "error.invalidcredentials": "Username or Password are incorrect", "patient.label.modify": "Add Or Modify Patient", "patient.label.info": "Patient Information", @@ -110,6 +111,7 @@ "sample.entry.project.patient.and.testName": "Name/Code of patient {br} Test Name", "label.button.remove": "Remove", "reject.order.sample.notification": "You are rejecting a sample. This sample will be rejected and not appear in workplans once saved,no results can be entered for this order.", + "analyzer.combinationName.notification": "The combination of analyzer and analyzer test name must be unique", "rulebuilder.label.ruleName": "Rule Name", "rulebuilder.label.toggleRule": "Toggle Rule", "rulebuilder.label.addRuleConditions": "Add Reflex Rule Conditions", @@ -273,6 +275,7 @@ "sidenav.label.admin.testmgt": "Test Management", "sidenav.label.admin.testmgt.reflex": "Reflex Tests Management", "sidenav.label.admin.testmgt.calculated": "Calculated Value Tests Management", + "sidenav.label.admin.analyzerTest": "Analyzer Test Name", "sidenav.label.admin.program": "Program Entry", "sidenav.label.admin.organizationmgt": "Organization Management", "sidenav.label.admin.usermgt": "User Management", @@ -285,6 +288,8 @@ "sidenav.label.admin.formEntry.resultConfig": "Result Entry Configuration", "sidenav.label.admin.formEntry.patientconfig": "Patient Entry Configuration", "sidenav.label.admin.formEntry.PrintedReportsconfig": "Printed Report Configuration", + "sidenav.label.admin.pluginFile": "Plugin Files", + "sidenav.label.admin.Listplugin": "List Plugins", "sidenav.title.statusreport": "Patient Status Report", "sidenav.label.statusreport": "Patient Status Report", "sidenav.title.aggregatereport": "Aggregate Reports", @@ -806,6 +811,7 @@ "label.test.add": "Add test to order", "label.add.notification": "Add pop up notification to user", "label.select.dateRange": "Select the Date Range you want the Report For", + "label.actualTestName": "Actual Test Name", "rulebuilder.label.add.internaltrigger": "Add Internal `triggered by` message", "rulebuilder.label.add.externaltrigger": "Add External `triggered by` message", "error.duplicate.calculationname": "Duplicate Calculation Name or Error while saving", @@ -904,7 +910,7 @@ "label.audittrailreport.sitename": "Site Name", "label.user.notestsection": "Current User has no Assined Lab Unit . Please Contact admin", "reports.label.cistudyexport": "General Report", - "header.label.study.ciexport": "Export a CSV File by Date Type", + "header.label.study.ciexport": "Export a CSV File by Date", "report.select.studttype": "Select Study Type", "error.report.csv.study": "Please select study type.", "error.report.csv.date": "Please select date type.", @@ -1036,6 +1042,10 @@ "organization.type.CI.name": "Type of Activity : Name", "organization.type.CI.description": "Type of Activity : Description", "organization.add.placeholder": "AlphaNumeric Values", + "organization.add.placeholder.internetAddress": "https://orgname.com", + "organization.search.parent.name": "Parent Organization Names", + "notification.organization.post.internetAddress": "Enter a valid Organization Url.", + "organization.add.placeholder.parent": "Parent Organization", "organization.add.placeholder.active": "Y or N", "organization.search.byorgname": "Search By Org Name", "organization.search.placeHolder": "Search By Org Name...", @@ -1050,5 +1060,35 @@ "organization.previous": "Previous Page", "organization.next": "Next Page", "showing": "Showing", - "of": "of" + "of": "of", + "results.label.refer": "Refer test to a reference lab", + "referral.label.referredOutTests": "ReferredOutTests", + "referral.out.head": "Referrals", + "referral.out.request": "Results By Date / Test / Unit Date Type :", + "referral.out.note": "Note if searching by result date, only tests with results will appear.", + "referral.date.start": "Start Date (dd/mm/yyyy)", + "referral.date.end": "End Date (dd/mm/yyyy)", + "referral.result.labNumber": "Results By Lab Number", + "referral.button.labSearch": "Search Referrals By Lab Number", + "referral.button.unitTestSearch": "Search Referrals By Unit(s) & Test(s)", + "referral.button.patientSearch": "Search Patient", + "referral.main.button": "Search Referrals By Patient", + "referral.units": "Unit(s)", + "referral.test": "Test(s)", + "referral.error": "No Referrals matching criteria", + "referral.input": "Scan OR Enter Manually", + "referral.search": "Search", + "referral.matching.search": "Referred Tests Matching Search", + "referral.print.selected.patient.reports": "Print Selected Patient Reports", + "referral.print.selected.patient.reports.selectnone.button": "Select None", + "referral.print.selected.patient.reports.selectall.button": "Select All", + "referral.search.column.resultDate": "Result Date", + "referral.search.column.sentDate": "Sent Date", + "referral.search.column.referenceLab": "Reference Lab", + "referral.search.column.analysisId": "AnalysisId", + "resultreporting.browse.title": "Result Reporting Configuration", + "testnotification.patiententry.info": "If OpenELIS is not able to connect to the recipient of the transmitted results it will queue them up. A large and growing queue is a sign that troubling shootingshould be done including contacting the receiving party.", + "resultreporting.config.url": "URL for site to which the results will be sent. For example http://192.168.56.101/someSite", + "resultreporting.config.url.placeholder": "https://orgname.com/someSite", + "result.report.queue.size": "Queue Size :" } diff --git a/frontend/src/languages/fr.json b/frontend/src/languages/fr.json index 2853823d5d..a337885516 100644 --- a/frontend/src/languages/fr.json +++ b/frontend/src/languages/fr.json @@ -254,6 +254,7 @@ "sidenav.label.admin.testmgt": "Gestion des Tests", "sidenav.label.admin.testmgt.reflex": "Gestion des tests de réflexes", "sidenav.label.admin.testmgt.calculated": "Gestion des tests de valeur calculée", + "sidenav.label.admin.analyzerTest": "Nom du test de l'analyseur", "sidenav.label.admin.program": "Entrée du Programme", "sidenav.label.admin.organizationmgt": "Gestion de l'Organisation", "sidenav.label.admin.usermgt": "Gestion des Utilisateurs", @@ -265,6 +266,7 @@ "sidenav.label.admin.formEntry.siteInfoconfig": "Informations sur le site", "sidenav.label.admin.formEntry.resultConfig": "Configuration de saisie de résultat", "sidenav.label.admin.formEntry.patientconfig": "Configuration de saisie du patient", + "sidenav.label.admin.pluginFile": "Fichiers de plugin", "sidenav.title.statusreport": "Rapport sur l'état du patient", "sidenav.label.statusreport": "Rapport sur l'état du patient", "sidenav.title.aggregatereport": "Rapports globaux", @@ -501,6 +503,7 @@ "cytology.label.dashboard": "Tableau de bord en cytologie", "label.button.start": "Commencer", "label.button.sample": "Échantillon", + "label.actualTestName": "Nom du test réel", "search.label.accession": "Saisissez le numéro d'accès", "search.label.testunit": "Sélectionnez l'unité de test", "search.label.testdate": "Saisissez la date du test", @@ -822,7 +825,7 @@ "label.audittrailreport.sitename": "Nom du site", "label.user.notestsection": "L'utilisateur actuel n'a pas d'unité de laboratoire assassinée. Veuillez contacter l'administrateur", "reports.label.cistudyexport": "Rapport général", - "header.label.study.ciexport": "Exporter un fichier CSV par type de date", + "header.label.study.ciexport": "Exporter un fichier CSV par date", "report.select.studttype": "Sélectionner le type d'étude", "error.report.csv.study": "Veuillez sélectionner le type d'étude.", "error.report.csv.date": "Veuillez sélectionner le type de date.", @@ -946,6 +949,9 @@ "organization.type.CI.select": "Type d'activité : Sélectionner", "organization.type.CI.name": "Type d'activité : Nom", "organization.type.CI.description": "Type d'activité : Description", + "organization.add.placeholder.internetAddress": "https://orgname.com", + "organization.search.parent.name": "Noms des organisations parentes", + "notification.organization.post.internetAddress": "Entrez une URL d'organisation valide.", "organization.add.placeholder": "Valeurs alphanumériques", "organization.add.placeholder.active": "Oui ou Non", "organization.search.byorgname": "Rechercher par nom d'organisation", @@ -961,5 +967,35 @@ "organization.previous": "Page précédente", "organization.next": "Page suivante", "showing": "Affichage", - "of": "de" + "of": "de", + "results.label.refer": "Référer le test à un laboratoire de référence", + "referral.label.referredOutTests": "Tests référés à l'extérieur", + "referral.out.head": "Références", + "referral.out.request": "Résultats par Date / Test / Type de Date d'Unité :", + "referral.out.note": "Notez que si vous recherchez par date de résultat, seuls les tests avec des résultats apparaîtront.", + "referral.date.start": "Date de Début (jj/mm/aaaa)", + "referral.date.end": "Date de Fin (jj/mm/aaaa)", + "referral.result.labNumber": "Résultats par Numéro de Laboratoire", + "referral.button.labSearch": "Rechercher les références par numéro de laboratoire", + "referral.button.unitTestSearch": "Rechercher les références par unité(s) et test(s)", + "referral.button.patientSearch": "Recherche de patient", + "referral.main.button": "Rechercher les références par patient", + "referral.units": "Unité(s)", + "referral.test": "Test(s)", + "referral.error": "Aucune référence ne correspond aux critères", + "referral.input": "Scanner ou Entrer Manuellement", + "referral.search": "Rechercher", + "referral.matching.search": "Tests référés correspondant à la recherche", + "referral.print.selected.patient.reports": "Imprimer les rapports des patients sélectionnés", + "referral.print.selected.patient.reports.selectnone.button": "Désélectionner tout", + "referral.print.selected.patient.reports.selectall.button": "Sélectionner tout", + "referral.search.column.resultDate": "Date de résultat", + "referral.search.column.sentDate": "Date d'envoi", + "referral.search.column.referenceLab": "Laboratoire de référence", + "referral.search.column.analysisId": "Identifiant de l'analyse", + "resultreporting.browse.title": "Configuration de la diffusion des résultats", + "testnotification.patiententry.info": "Si OpenELIS n'est pas en mesure de se connecter au destinataire des résultats transmis, il les mettra en file d'attente. Une file d'attente grande et croissante est un signe qu'il faut entreprendre des actions correctives, y compris contacter la partie réceptrice.", + "resultreporting.config.url": "URL du site vers lequel les résultats seront envoyés. Par exemple http://192.168.56.101/someSite", + "resultreporting.config.url.placeholder": "https://nomdelorganisation.com/someSite", + "result.report.queue.size": "Taille de la file d'attente :" } diff --git a/pom.xml b/pom.xml index 772a2a748f..45fb140602 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ 8 1 - 35 + 36 UTF-8 ${project.basedir}/liquibase/liquibase.properties 1.4.1 @@ -667,12 +667,10 @@ - - - 1.15.0 - - true - + + 4.26 + ${project.basedir}/tools/OpenELIS_java_formatter.xml + diff --git a/src/main/java/org/openelisglobal/action/dao/ActionDAO.java b/src/main/java/org/openelisglobal/action/dao/ActionDAO.java index 065c70074c..f58605b183 100644 --- a/src/main/java/org/openelisglobal/action/dao/ActionDAO.java +++ b/src/main/java/org/openelisglobal/action/dao/ActionDAO.java @@ -3,4 +3,5 @@ import org.openelisglobal.action.valueholder.Action; import org.openelisglobal.common.dao.BaseDAO; -public interface ActionDAO extends BaseDAO {} +public interface ActionDAO extends BaseDAO { +} diff --git a/src/main/java/org/openelisglobal/action/dao/ActionDAOImpl.java b/src/main/java/org/openelisglobal/action/dao/ActionDAOImpl.java index 94d1d8b5d4..6cd5ad13a8 100644 --- a/src/main/java/org/openelisglobal/action/dao/ActionDAOImpl.java +++ b/src/main/java/org/openelisglobal/action/dao/ActionDAOImpl.java @@ -8,7 +8,7 @@ @Component @Transactional public class ActionDAOImpl extends BaseDAOImpl implements ActionDAO { - ActionDAOImpl() { - super(Action.class); - } + ActionDAOImpl() { + super(Action.class); + } } diff --git a/src/main/java/org/openelisglobal/action/service/ActionService.java b/src/main/java/org/openelisglobal/action/service/ActionService.java index 792275c27e..76b6eebd98 100644 --- a/src/main/java/org/openelisglobal/action/service/ActionService.java +++ b/src/main/java/org/openelisglobal/action/service/ActionService.java @@ -3,4 +3,5 @@ import org.openelisglobal.action.valueholder.Action; import org.openelisglobal.common.service.BaseObjectService; -public interface ActionService extends BaseObjectService {} +public interface ActionService extends BaseObjectService { +} diff --git a/src/main/java/org/openelisglobal/action/service/ActionServiceImpl.java b/src/main/java/org/openelisglobal/action/service/ActionServiceImpl.java index 3fa7744db7..9a4c8056cb 100644 --- a/src/main/java/org/openelisglobal/action/service/ActionServiceImpl.java +++ b/src/main/java/org/openelisglobal/action/service/ActionServiceImpl.java @@ -7,16 +7,16 @@ import org.springframework.stereotype.Service; @Service -public class ActionServiceImpl extends AuditableBaseObjectServiceImpl - implements ActionService { - @Autowired protected ActionDAO baseObjectDAO; +public class ActionServiceImpl extends AuditableBaseObjectServiceImpl implements ActionService { + @Autowired + protected ActionDAO baseObjectDAO; - ActionServiceImpl() { - super(Action.class); - } + ActionServiceImpl() { + super(Action.class); + } - @Override - protected ActionDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected ActionDAO getBaseObjectDAO() { + return baseObjectDAO; + } } diff --git a/src/main/java/org/openelisglobal/action/valueholder/Action.java b/src/main/java/org/openelisglobal/action/valueholder/Action.java index f8e5cb2d00..390124f1dd 100644 --- a/src/main/java/org/openelisglobal/action/valueholder/Action.java +++ b/src/main/java/org/openelisglobal/action/valueholder/Action.java @@ -18,59 +18,59 @@ public class Action extends BaseObject { - private String code; + private String code; - private String id; + private String id; - private String description; + private String description; - private String type; + private String type; - // (concatenate action code name/desc) - private String actionDisplayValue; + // (concatenate action code name/desc) + private String actionDisplayValue; - public Action() { - super(); - } + public Action() { + super(); + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getActionDisplayValue() { - if (!StringUtil.isNullorNill(this.code)) { - actionDisplayValue = code + "-" + description; - } else { - actionDisplayValue = description; + public String getActionDisplayValue() { + if (!StringUtil.isNullorNill(this.code)) { + actionDisplayValue = code + "-" + description; + } else { + actionDisplayValue = description; + } + return actionDisplayValue; } - return actionDisplayValue; - } } diff --git a/src/main/java/org/openelisglobal/address/dao/AddressPartDAO.java b/src/main/java/org/openelisglobal/address/dao/AddressPartDAO.java index 154303786e..55db6159a6 100644 --- a/src/main/java/org/openelisglobal/address/dao/AddressPartDAO.java +++ b/src/main/java/org/openelisglobal/address/dao/AddressPartDAO.java @@ -16,4 +16,5 @@ import org.openelisglobal.address.valueholder.AddressPart; import org.openelisglobal.common.dao.BaseDAO; -public interface AddressPartDAO extends BaseDAO {} +public interface AddressPartDAO extends BaseDAO { +} diff --git a/src/main/java/org/openelisglobal/address/dao/OrganizationAddressDAO.java b/src/main/java/org/openelisglobal/address/dao/OrganizationAddressDAO.java index 0e0761fedb..9c55ed919e 100644 --- a/src/main/java/org/openelisglobal/address/dao/OrganizationAddressDAO.java +++ b/src/main/java/org/openelisglobal/address/dao/OrganizationAddressDAO.java @@ -21,8 +21,8 @@ public interface OrganizationAddressDAO extends BaseDAO { - List getAddressPartsByOrganizationId(String organizationId) - throws LIMSRuntimeException; + List getAddressPartsByOrganizationId(String organizationId) throws LIMSRuntimeException; - // public Optional update(OrganizationAddress organizationAddress); + // public Optional update(OrganizationAddress + // organizationAddress); } diff --git a/src/main/java/org/openelisglobal/address/dao/PersonAddressDAO.java b/src/main/java/org/openelisglobal/address/dao/PersonAddressDAO.java index ea57723312..1f01667369 100644 --- a/src/main/java/org/openelisglobal/address/dao/PersonAddressDAO.java +++ b/src/main/java/org/openelisglobal/address/dao/PersonAddressDAO.java @@ -21,8 +21,7 @@ public interface PersonAddressDAO extends BaseDAO { - List getAddressPartsByPersonId(String personId) throws LIMSRuntimeException; + List getAddressPartsByPersonId(String personId) throws LIMSRuntimeException; - PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) - throws LIMSRuntimeException; + PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) throws LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/address/daoimpl/AddressPartDAOImpl.java b/src/main/java/org/openelisglobal/address/daoimpl/AddressPartDAOImpl.java index 95cfc699b1..ea498b853a 100644 --- a/src/main/java/org/openelisglobal/address/daoimpl/AddressPartDAOImpl.java +++ b/src/main/java/org/openelisglobal/address/daoimpl/AddressPartDAOImpl.java @@ -23,7 +23,7 @@ @Transactional public class AddressPartDAOImpl extends BaseDAOImpl implements AddressPartDAO { - public AddressPartDAOImpl() { - super(AddressPart.class); - } + public AddressPartDAOImpl() { + super(AddressPart.class); + } } diff --git a/src/main/java/org/openelisglobal/address/daoimpl/OrganizationAddressDAOImpl.java b/src/main/java/org/openelisglobal/address/daoimpl/OrganizationAddressDAOImpl.java index a25a67fe7c..7c75d31342 100644 --- a/src/main/java/org/openelisglobal/address/daoimpl/OrganizationAddressDAOImpl.java +++ b/src/main/java/org/openelisglobal/address/daoimpl/OrganizationAddressDAOImpl.java @@ -28,27 +28,27 @@ @Component @Transactional public class OrganizationAddressDAOImpl extends BaseDAOImpl - implements OrganizationAddressDAO { + implements OrganizationAddressDAO { - public OrganizationAddressDAOImpl() { - super(OrganizationAddress.class); - } + public OrganizationAddressDAOImpl() { + super(OrganizationAddress.class); + } - @Override - public List getAddressPartsByOrganizationId(String organizationId) - throws LIMSRuntimeException { - String sql = "from OrganizationAddress pa where pa.compoundId.targetId = :organizationId"; + @Override + public List getAddressPartsByOrganizationId(String organizationId) + throws LIMSRuntimeException { + String sql = "from OrganizationAddress pa where pa.compoundId.targetId = :organizationId"; - try { - Query query = - entityManager.unwrap(Session.class).createQuery(sql, OrganizationAddress.class); - query.setParameter("organizationId", Integer.parseInt(organizationId)); - List addressPartList = query.list(); - return addressPartList; - } catch (HibernateException e) { - handleException(e, "getAddressPartsByOrganizationId"); - } + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, + OrganizationAddress.class); + query.setParameter("organizationId", Integer.parseInt(organizationId)); + List addressPartList = query.list(); + return addressPartList; + } catch (HibernateException e) { + handleException(e, "getAddressPartsByOrganizationId"); + } - return null; - } + return null; + } } diff --git a/src/main/java/org/openelisglobal/address/daoimpl/PersonAddressDAOImpl.java b/src/main/java/org/openelisglobal/address/daoimpl/PersonAddressDAOImpl.java index 564dd5261b..d321f75d98 100644 --- a/src/main/java/org/openelisglobal/address/daoimpl/PersonAddressDAOImpl.java +++ b/src/main/java/org/openelisglobal/address/daoimpl/PersonAddressDAOImpl.java @@ -27,49 +27,43 @@ @Component @Transactional -public class PersonAddressDAOImpl extends BaseDAOImpl - implements PersonAddressDAO { +public class PersonAddressDAOImpl extends BaseDAOImpl implements PersonAddressDAO { - public PersonAddressDAOImpl() { - super(PersonAddress.class); - } + public PersonAddressDAOImpl() { + super(PersonAddress.class); + } + + @Override + public List getAddressPartsByPersonId(String personId) throws LIMSRuntimeException { + String sql = "from PersonAddress pa where pa.compoundId.targetId = :personId"; - @Override - public List getAddressPartsByPersonId(String personId) - throws LIMSRuntimeException { - String sql = "from PersonAddress pa where pa.compoundId.targetId = :personId"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, PersonAddress.class); + query.setParameter("personId", Integer.parseInt(personId)); + List addressPartList = query.list(); + return addressPartList; + } catch (HibernateException e) { + handleException(e, "getAddressPartsByPersonId"); + } - try { - Query query = - entityManager.unwrap(Session.class).createQuery(sql, PersonAddress.class); - query.setParameter("personId", Integer.parseInt(personId)); - List addressPartList = query.list(); - return addressPartList; - } catch (HibernateException e) { - handleException(e, "getAddressPartsByPersonId"); + return null; } - return null; - } + @Override + public PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) throws LIMSRuntimeException { + String sql = "from PersonAddress pa where pa.compoundId.targetId = :personId and" + + " pa.compoundId.addressPartId = :partId"; - @Override - public PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) - throws LIMSRuntimeException { - String sql = - "from PersonAddress pa where pa.compoundId.targetId = :personId and" - + " pa.compoundId.addressPartId = :partId"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, PersonAddress.class); + query.setParameter("personId", Integer.parseInt(personId)); + query.setParameter("partId", Integer.parseInt(addressPartId)); + PersonAddress addressPart = query.uniqueResult(); + return addressPart; + } catch (HibernateException e) { + handleException(e, "getByPersonIdAndPartId"); + } - try { - Query query = - entityManager.unwrap(Session.class).createQuery(sql, PersonAddress.class); - query.setParameter("personId", Integer.parseInt(personId)); - query.setParameter("partId", Integer.parseInt(addressPartId)); - PersonAddress addressPart = query.uniqueResult(); - return addressPart; - } catch (HibernateException e) { - handleException(e, "getByPersonIdAndPartId"); + return null; } - - return null; - } } diff --git a/src/main/java/org/openelisglobal/address/service/AddressPartService.java b/src/main/java/org/openelisglobal/address/service/AddressPartService.java index e60698af60..3066436c87 100644 --- a/src/main/java/org/openelisglobal/address/service/AddressPartService.java +++ b/src/main/java/org/openelisglobal/address/service/AddressPartService.java @@ -5,7 +5,7 @@ import org.openelisglobal.common.service.BaseObjectService; public interface AddressPartService extends BaseObjectService { - List getAll(); + List getAll(); - AddressPart getAddresPartByName(String name); + AddressPart getAddresPartByName(String name); } diff --git a/src/main/java/org/openelisglobal/address/service/AddressPartServiceImpl.java b/src/main/java/org/openelisglobal/address/service/AddressPartServiceImpl.java index 09af2e1e12..98d11d2d7b 100644 --- a/src/main/java/org/openelisglobal/address/service/AddressPartServiceImpl.java +++ b/src/main/java/org/openelisglobal/address/service/AddressPartServiceImpl.java @@ -9,21 +9,22 @@ @Service public class AddressPartServiceImpl extends AuditableBaseObjectServiceImpl - implements AddressPartService { - @Autowired protected AddressPartDAO baseObjectDAO; + implements AddressPartService { + @Autowired + protected AddressPartDAO baseObjectDAO; - public AddressPartServiceImpl() { - super(AddressPart.class); - } + public AddressPartServiceImpl() { + super(AddressPart.class); + } - @Override - protected AddressPartDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected AddressPartDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - @Transactional(readOnly = true) - public AddressPart getAddresPartByName(String name) { - return getMatch("partName", name).orElse(null); - } + @Override + @Transactional(readOnly = true) + public AddressPart getAddresPartByName(String name) { + return getMatch("partName", name).orElse(null); + } } diff --git a/src/main/java/org/openelisglobal/address/service/OrganizationAddressService.java b/src/main/java/org/openelisglobal/address/service/OrganizationAddressService.java index def19990d2..4b1e31ced9 100644 --- a/src/main/java/org/openelisglobal/address/service/OrganizationAddressService.java +++ b/src/main/java/org/openelisglobal/address/service/OrganizationAddressService.java @@ -5,8 +5,7 @@ import org.openelisglobal.address.valueholder.OrganizationAddress; import org.openelisglobal.common.service.BaseObjectService; -public interface OrganizationAddressService - extends BaseObjectService { +public interface OrganizationAddressService extends BaseObjectService { - List getAddressPartsByOrganizationId(String organizationId); + List getAddressPartsByOrganizationId(String organizationId); } diff --git a/src/main/java/org/openelisglobal/address/service/OrganizationAddressServiceImpl.java b/src/main/java/org/openelisglobal/address/service/OrganizationAddressServiceImpl.java index ba217ffcfa..2f6e190c8b 100644 --- a/src/main/java/org/openelisglobal/address/service/OrganizationAddressServiceImpl.java +++ b/src/main/java/org/openelisglobal/address/service/OrganizationAddressServiceImpl.java @@ -11,24 +11,24 @@ import org.springframework.transaction.annotation.Transactional; @Service -public class OrganizationAddressServiceImpl - extends AuditableBaseObjectServiceImpl - implements OrganizationAddressService { - @Autowired protected OrganizationAddressDAO baseObjectDAO; +public class OrganizationAddressServiceImpl extends AuditableBaseObjectServiceImpl + implements OrganizationAddressService { + @Autowired + protected OrganizationAddressDAO baseObjectDAO; - OrganizationAddressServiceImpl() { - super(OrganizationAddress.class); - defaultSortOrder = new ArrayList<>(); - } + OrganizationAddressServiceImpl() { + super(OrganizationAddress.class); + defaultSortOrder = new ArrayList<>(); + } - @Override - protected OrganizationAddressDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected OrganizationAddressDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - @Transactional(readOnly = true) - public List getAddressPartsByOrganizationId(String organizationId) { - return baseObjectDAO.getAddressPartsByOrganizationId(organizationId); - } + @Override + @Transactional(readOnly = true) + public List getAddressPartsByOrganizationId(String organizationId) { + return baseObjectDAO.getAddressPartsByOrganizationId(organizationId); + } } diff --git a/src/main/java/org/openelisglobal/address/service/PersonAddressService.java b/src/main/java/org/openelisglobal/address/service/PersonAddressService.java index e386dd4a15..96fd73c8cb 100644 --- a/src/main/java/org/openelisglobal/address/service/PersonAddressService.java +++ b/src/main/java/org/openelisglobal/address/service/PersonAddressService.java @@ -7,10 +7,10 @@ public interface PersonAddressService extends BaseObjectService { - @Override - AddressPK insert(PersonAddress personAddress); + @Override + AddressPK insert(PersonAddress personAddress); - List getAddressPartsByPersonId(String personId); + List getAddressPartsByPersonId(String personId); - PersonAddress getByPersonIdAndPartId(String personId, String addressPartId); + PersonAddress getByPersonIdAndPartId(String personId, String addressPartId); } diff --git a/src/main/java/org/openelisglobal/address/service/PersonAddressServiceImpl.java b/src/main/java/org/openelisglobal/address/service/PersonAddressServiceImpl.java index 23635f1825..5a49828200 100644 --- a/src/main/java/org/openelisglobal/address/service/PersonAddressServiceImpl.java +++ b/src/main/java/org/openelisglobal/address/service/PersonAddressServiceImpl.java @@ -11,35 +11,35 @@ import org.springframework.transaction.annotation.Transactional; @Service -public class PersonAddressServiceImpl - extends AuditableBaseObjectServiceImpl - implements PersonAddressService { - @Autowired protected PersonAddressDAO baseObjectDAO; +public class PersonAddressServiceImpl extends AuditableBaseObjectServiceImpl + implements PersonAddressService { + @Autowired + protected PersonAddressDAO baseObjectDAO; - PersonAddressServiceImpl() { - super(PersonAddress.class); - defaultSortOrder = new ArrayList<>(); - } + PersonAddressServiceImpl() { + super(PersonAddress.class); + defaultSortOrder = new ArrayList<>(); + } - @Override - protected PersonAddressDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected PersonAddressDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - @Transactional(readOnly = true) - public List getAddressPartsByPersonId(String personId) { - return baseObjectDAO.getAddressPartsByPersonId(personId); - } + @Override + @Transactional(readOnly = true) + public List getAddressPartsByPersonId(String personId) { + return baseObjectDAO.getAddressPartsByPersonId(personId); + } - @Override - @Transactional(readOnly = true) - public PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) { - return baseObjectDAO.getByPersonIdAndPartId(personId, addressPartId); - } + @Override + @Transactional(readOnly = true) + public PersonAddress getByPersonIdAndPartId(String personId, String addressPartId) { + return baseObjectDAO.getByPersonIdAndPartId(personId, addressPartId); + } - @Override - public AddressPK insert(PersonAddress personAddress) { - return super.insert(personAddress); - } + @Override + public AddressPK insert(PersonAddress personAddress) { + return super.insert(personAddress); + } } diff --git a/src/main/java/org/openelisglobal/address/valueholder/AddressPK.java b/src/main/java/org/openelisglobal/address/valueholder/AddressPK.java index af1e5e6165..fd2ef96b81 100644 --- a/src/main/java/org/openelisglobal/address/valueholder/AddressPK.java +++ b/src/main/java/org/openelisglobal/address/valueholder/AddressPK.java @@ -18,38 +18,39 @@ public class AddressPK implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private String targetId; - private String addressPartId; + private String targetId; + private String addressPartId; - public String getTargetId() { - return targetId; - } + public String getTargetId() { + return targetId; + } - public void setTargetId(String targetId) { - this.targetId = targetId; - } + public void setTargetId(String targetId) { + this.targetId = targetId; + } - public String getAddressPartId() { - return addressPartId; - } + public String getAddressPartId() { + return addressPartId; + } - public void setAddressPartId(String addressPartId) { - this.addressPartId = addressPartId; - } + public void setAddressPartId(String addressPartId) { + this.addressPartId = addressPartId; + } - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; - AddressPK that = (AddressPK) o; + AddressPK that = (AddressPK) o; - return Objects.equals(this.targetId, that.targetId) - && Objects.equals(this.addressPartId, that.addressPartId); - } + return Objects.equals(this.targetId, that.targetId) && Objects.equals(this.addressPartId, that.addressPartId); + } - public int hashCode() { - return Objects.hash(targetId, addressPartId); - } + public int hashCode() { + return Objects.hash(targetId, addressPartId); + } } diff --git a/src/main/java/org/openelisglobal/address/valueholder/AddressPart.java b/src/main/java/org/openelisglobal/address/valueholder/AddressPart.java index c93d9a6258..4b726e4acc 100644 --- a/src/main/java/org/openelisglobal/address/valueholder/AddressPart.java +++ b/src/main/java/org/openelisglobal/address/valueholder/AddressPart.java @@ -17,33 +17,33 @@ public class AddressPart extends BaseObject { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private String id; - private String partName; - private String displayOrder; + private String id; + private String partName; + private String displayOrder; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getPartName() { - return partName; - } + public String getPartName() { + return partName; + } - public void setPartName(String partName) { - this.partName = partName; - } + public void setPartName(String partName) { + this.partName = partName; + } - public String getDisplayOrder() { - return displayOrder; - } + public String getDisplayOrder() { + return displayOrder; + } - public void setDisplayOrder(String displayOrder) { - this.displayOrder = displayOrder; - } + public void setDisplayOrder(String displayOrder) { + this.displayOrder = displayOrder; + } } diff --git a/src/main/java/org/openelisglobal/address/valueholder/OrganizationAddress.java b/src/main/java/org/openelisglobal/address/valueholder/OrganizationAddress.java index f51fcb602d..006ce99338 100644 --- a/src/main/java/org/openelisglobal/address/valueholder/OrganizationAddress.java +++ b/src/main/java/org/openelisglobal/address/valueholder/OrganizationAddress.java @@ -18,79 +18,79 @@ public class OrganizationAddress extends BaseObject { - private static final long serialVersionUID = 1L; - - private AddressPK compoundId = new AddressPK(); - private String type; - private String value; - private String uniqueIdentifyer; - - public AddressPK getCompoundId() { - return compoundId; - } - - public void setCompoundId(AddressPK compoundId) { - uniqueIdentifyer = null; - this.compoundId = compoundId; - } - - public String getStringId() { - return compoundId == null ? "0" : compoundId.getTargetId() + compoundId.getAddressPartId(); - } - - @Override - public void setId(AddressPK id) { - setCompoundId(id); - } - - @Override - public AddressPK getId() { - return getCompoundId(); - } - - public void setOrganizationId(String organizationId) { - uniqueIdentifyer = null; - compoundId.setTargetId(organizationId); - } - - public String getOrganizationId() { - return compoundId == null ? null : compoundId.getTargetId(); - } - - public void setAddressPartId(String addressPartId) { - uniqueIdentifyer = null; - compoundId.setAddressPartId(addressPartId); - } - - public String getAddressPartId() { - return compoundId == null ? null : compoundId.getAddressPartId(); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public void setUniqueIdentifyer(String uniqueIdentifyer) { - this.uniqueIdentifyer = uniqueIdentifyer; - } - - public String getUniqueIdentifyer() { - if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { - uniqueIdentifyer = getOrganizationId() + "-" + getAddressPartId(); + private static final long serialVersionUID = 1L; + + private AddressPK compoundId = new AddressPK(); + private String type; + private String value; + private String uniqueIdentifyer; + + public AddressPK getCompoundId() { + return compoundId; + } + + public void setCompoundId(AddressPK compoundId) { + uniqueIdentifyer = null; + this.compoundId = compoundId; + } + + public String getStringId() { + return compoundId == null ? "0" : compoundId.getTargetId() + compoundId.getAddressPartId(); + } + + @Override + public void setId(AddressPK id) { + setCompoundId(id); + } + + @Override + public AddressPK getId() { + return getCompoundId(); + } + + public void setOrganizationId(String organizationId) { + uniqueIdentifyer = null; + compoundId.setTargetId(organizationId); + } + + public String getOrganizationId() { + return compoundId == null ? null : compoundId.getTargetId(); + } + + public void setAddressPartId(String addressPartId) { + uniqueIdentifyer = null; + compoundId.setAddressPartId(addressPartId); + } + + public String getAddressPartId() { + return compoundId == null ? null : compoundId.getAddressPartId(); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; } - return uniqueIdentifyer; - } + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public void setUniqueIdentifyer(String uniqueIdentifyer) { + this.uniqueIdentifyer = uniqueIdentifyer; + } + + public String getUniqueIdentifyer() { + if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { + uniqueIdentifyer = getOrganizationId() + "-" + getAddressPartId(); + } + + return uniqueIdentifyer; + } } diff --git a/src/main/java/org/openelisglobal/address/valueholder/PersonAddress.java b/src/main/java/org/openelisglobal/address/valueholder/PersonAddress.java index bf78f4ec67..d6e88f6bcd 100644 --- a/src/main/java/org/openelisglobal/address/valueholder/PersonAddress.java +++ b/src/main/java/org/openelisglobal/address/valueholder/PersonAddress.java @@ -18,79 +18,79 @@ public class PersonAddress extends BaseObject { - private static final long serialVersionUID = 1L; - - private AddressPK compoundId = new AddressPK(); - private String type; - private String value; - private String uniqueIdentifyer; - - public AddressPK getCompoundId() { - return compoundId; - } - - public void setCompoundId(AddressPK compoundId) { - uniqueIdentifyer = null; - this.compoundId = compoundId; - } - - public String getStringId() { - return compoundId == null ? "0" : compoundId.getTargetId() + compoundId.getAddressPartId(); - } - - @Override - public void setId(AddressPK id) { - setCompoundId(id); - } - - @Override - public AddressPK getId() { - return getCompoundId(); - } - - public void setPersonId(String personId) { - uniqueIdentifyer = null; - compoundId.setTargetId(personId); - } - - public String getPersonId() { - return compoundId == null ? null : compoundId.getTargetId(); - } - - public void setAddressPartId(String addressPartId) { - uniqueIdentifyer = null; - compoundId.setAddressPartId(addressPartId); - } - - public String getAddressPartId() { - return compoundId == null ? null : compoundId.getAddressPartId(); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public void setUniqueIdentifyer(String uniqueIdentifyer) { - this.uniqueIdentifyer = uniqueIdentifyer; - } - - public String getUniqueIdentifyer() { - if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { - uniqueIdentifyer = getPersonId() + "-" + getAddressPartId(); + private static final long serialVersionUID = 1L; + + private AddressPK compoundId = new AddressPK(); + private String type; + private String value; + private String uniqueIdentifyer; + + public AddressPK getCompoundId() { + return compoundId; + } + + public void setCompoundId(AddressPK compoundId) { + uniqueIdentifyer = null; + this.compoundId = compoundId; + } + + public String getStringId() { + return compoundId == null ? "0" : compoundId.getTargetId() + compoundId.getAddressPartId(); + } + + @Override + public void setId(AddressPK id) { + setCompoundId(id); + } + + @Override + public AddressPK getId() { + return getCompoundId(); + } + + public void setPersonId(String personId) { + uniqueIdentifyer = null; + compoundId.setTargetId(personId); + } + + public String getPersonId() { + return compoundId == null ? null : compoundId.getTargetId(); + } + + public void setAddressPartId(String addressPartId) { + uniqueIdentifyer = null; + compoundId.setAddressPartId(addressPartId); + } + + public String getAddressPartId() { + return compoundId == null ? null : compoundId.getAddressPartId(); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; } - return uniqueIdentifyer; - } + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public void setUniqueIdentifyer(String uniqueIdentifyer) { + this.uniqueIdentifyer = uniqueIdentifyer; + } + + public String getUniqueIdentifyer() { + if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { + uniqueIdentifyer = getPersonId() + "-" + getAddressPartId(); + } + + return uniqueIdentifyer; + } } diff --git a/src/main/java/org/openelisglobal/admin/controller/ImportController.java b/src/main/java/org/openelisglobal/admin/controller/ImportController.java index 3fc54cd047..a0af90b83b 100644 --- a/src/main/java/org/openelisglobal/admin/controller/ImportController.java +++ b/src/main/java/org/openelisglobal/admin/controller/ImportController.java @@ -14,21 +14,19 @@ @RequestMapping("/import") public class ImportController { - @GetMapping(value = "/all") - public void importAll() throws FhirLocalPersistingException, FhirGeneralException, IOException { - SpringContext.getBean(OrganizationImportService.class).importOrganizationList(); - SpringContext.getBean(ProviderImportService.class).importPractitionerList(); - } + @GetMapping(value = "/all") + public void importAll() throws FhirLocalPersistingException, FhirGeneralException, IOException { + SpringContext.getBean(OrganizationImportService.class).importOrganizationList(); + SpringContext.getBean(ProviderImportService.class).importPractitionerList(); + } - @GetMapping(value = "/organization") - public void importOrganizations() - throws FhirLocalPersistingException, FhirGeneralException, IOException { - SpringContext.getBean(OrganizationImportService.class).importOrganizationList(); - } + @GetMapping(value = "/organization") + public void importOrganizations() throws FhirLocalPersistingException, FhirGeneralException, IOException { + SpringContext.getBean(OrganizationImportService.class).importOrganizationList(); + } - @GetMapping(value = "/provider") - public void importProviders() - throws FhirLocalPersistingException, FhirGeneralException, IOException { - SpringContext.getBean(ProviderImportService.class).importPractitionerList(); - } + @GetMapping(value = "/provider") + public void importProviders() throws FhirLocalPersistingException, FhirGeneralException, IOException { + SpringContext.getBean(ProviderImportService.class).importPractitionerList(); + } } diff --git a/src/main/java/org/openelisglobal/admin/controller/LabNumberManagementController.java b/src/main/java/org/openelisglobal/admin/controller/LabNumberManagementController.java index 84ed0d3d11..23b71abe9e 100644 --- a/src/main/java/org/openelisglobal/admin/controller/LabNumberManagementController.java +++ b/src/main/java/org/openelisglobal/admin/controller/LabNumberManagementController.java @@ -17,39 +17,34 @@ @RestController public class LabNumberManagementController { - @Autowired private SiteInformationService siteInformationService; - - @GetMapping("/rest/labnumbermanagement") - public LabNumberManagementForm getValues() { - LabNumberManagementForm form = new LabNumberManagementForm(); - - form.setAlphanumPrefix( - ConfigurationProperties.getInstance() - .getPropertyValueUpperCase(Property.ALPHANUM_ACCESSION_PREFIX)); - form.setLabNumberType( - AccessionFormat.valueOf( - ConfigurationProperties.getInstance().getPropertyValue(Property.AccessionFormat))); - form.setUsePrefix( - "true" - .equals( - ConfigurationProperties.getInstance() - .getPropertyValue(Property.USE_ALPHANUM_ACCESSION_PREFIX))); - - return form; - } - - @PostMapping("/rest/labnumbermanagement") - public LabNumberManagementForm setValues(@Valid @RequestBody LabNumberManagementForm form) { - Map map = new HashMap<>(); - - map.put( - Property.ALPHANUM_ACCESSION_PREFIX.getName(), - form.getAlphanumPrefix() != null ? form.getAlphanumPrefix().toUpperCase() : ""); - map.put(Property.AccessionFormat.getName(), form.getLabNumberType().name()); - map.put(Property.USE_ALPHANUM_ACCESSION_PREFIX.getName(), form.getUsePrefix().toString()); - siteInformationService.updateSiteInformationByName(map); - - ConfigurationProperties.forceReload(); - return form; - } + @Autowired + private SiteInformationService siteInformationService; + + @GetMapping("/rest/labnumbermanagement") + public LabNumberManagementForm getValues() { + LabNumberManagementForm form = new LabNumberManagementForm(); + + form.setAlphanumPrefix( + ConfigurationProperties.getInstance().getPropertyValueUpperCase(Property.ALPHANUM_ACCESSION_PREFIX)); + form.setLabNumberType(AccessionFormat + .valueOf(ConfigurationProperties.getInstance().getPropertyValue(Property.AccessionFormat))); + form.setUsePrefix("true".equals( + ConfigurationProperties.getInstance().getPropertyValue(Property.USE_ALPHANUM_ACCESSION_PREFIX))); + + return form; + } + + @PostMapping("/rest/labnumbermanagement") + public LabNumberManagementForm setValues(@Valid @RequestBody LabNumberManagementForm form) { + Map map = new HashMap<>(); + + map.put(Property.ALPHANUM_ACCESSION_PREFIX.getName(), + form.getAlphanumPrefix() != null ? form.getAlphanumPrefix().toUpperCase() : ""); + map.put(Property.AccessionFormat.getName(), form.getLabNumberType().name()); + map.put(Property.USE_ALPHANUM_ACCESSION_PREFIX.getName(), form.getUsePrefix().toString()); + siteInformationService.updateSiteInformationByName(map); + + ConfigurationProperties.forceReload(); + return form; + } } diff --git a/src/main/java/org/openelisglobal/admin/form/LabNumberManagementForm.java b/src/main/java/org/openelisglobal/admin/form/LabNumberManagementForm.java index 743a26d362..50823a25a1 100644 --- a/src/main/java/org/openelisglobal/admin/form/LabNumberManagementForm.java +++ b/src/main/java/org/openelisglobal/admin/form/LabNumberManagementForm.java @@ -6,35 +6,35 @@ public class LabNumberManagementForm { - private AccessionFormat labNumberType; + private AccessionFormat labNumberType; - private Boolean usePrefix; + private Boolean usePrefix; - @Length(max = 5, min = 0) - @SafeHtml - private String alphanumPrefix; + @Length(max = 5, min = 0) + @SafeHtml + private String alphanumPrefix; - public AccessionFormat getLabNumberType() { - return labNumberType; - } + public AccessionFormat getLabNumberType() { + return labNumberType; + } - public void setLabNumberType(AccessionFormat labNumberType) { - this.labNumberType = labNumberType; - } + public void setLabNumberType(AccessionFormat labNumberType) { + this.labNumberType = labNumberType; + } - public Boolean getUsePrefix() { - return usePrefix; - } + public Boolean getUsePrefix() { + return usePrefix; + } - public void setUsePrefix(Boolean usePrefix) { - this.usePrefix = usePrefix; - } + public void setUsePrefix(Boolean usePrefix) { + this.usePrefix = usePrefix; + } - public String getAlphanumPrefix() { - return alphanumPrefix; - } + public String getAlphanumPrefix() { + return alphanumPrefix; + } - public void setAlphanumPrefix(String alphanumPrefix) { - this.alphanumPrefix = alphanumPrefix; - } + public void setAlphanumPrefix(String alphanumPrefix) { + this.alphanumPrefix = alphanumPrefix; + } } diff --git a/src/main/java/org/openelisglobal/analysis/dao/AnalysisDAO.java b/src/main/java/org/openelisglobal/analysis/dao/AnalysisDAO.java index f08123c375..2e0fc53883 100644 --- a/src/main/java/org/openelisglobal/analysis/dao/AnalysisDAO.java +++ b/src/main/java/org/openelisglobal/analysis/dao/AnalysisDAO.java @@ -31,234 +31,214 @@ /** * @author diane benz - *

To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>Templates. To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + *

+ * To change this generated comment edit the template variable + * "typecomment": Window>Preferences>Java>Templates. To enable and + * disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. */ public interface AnalysisDAO extends BaseDAO { - // boolean insertData(Analysis analysis, boolean duplicateCheck) throws LIMSRuntimeException; + // boolean insertData(Analysis analysis, boolean duplicateCheck) throws + // LIMSRuntimeException; - // - // void deleteData(List analysiss) throws LIMSRuntimeException; + // + // void deleteData(List analysiss) throws LIMSRuntimeException; - // - // List getAllAnalyses() throws LIMSRuntimeException; + // + // List getAllAnalyses() throws LIMSRuntimeException; - // - // List getPageOfAnalyses(int startingRecNo) throws LIMSRuntimeException; + // + // List getPageOfAnalyses(int startingRecNo) throws LIMSRuntimeException; - void getData(Analysis analysis) throws LIMSRuntimeException; + void getData(Analysis analysis) throws LIMSRuntimeException; - // void updateData(Analysis analysis) throws LIMSRuntimeException; + // void updateData(Analysis analysis) throws LIMSRuntimeException; - // - // List getAnalyses(String filter) throws LIMSRuntimeException; + // + // List getAnalyses(String filter) throws LIMSRuntimeException; - // + // - // - // + // + // - // - // List getAllAnalysesPerTest(Test test) throws LIMSRuntimeException; + // + // List getAllAnalysesPerTest(Test test) throws LIMSRuntimeException; - List getAllAnalysisByTestAndStatus(String testId, List statusIdList) - throws LIMSRuntimeException; + List getAllAnalysisByTestAndStatus(String testId, List statusIdList) throws LIMSRuntimeException; - List getAllAnalysisByTestsAndStatus(List testIdList, List statusIdList) - throws LIMSRuntimeException; + List getAllAnalysisByTestsAndStatus(List testIdList, List statusIdList) + throws LIMSRuntimeException; - List getAllAnalysisByTestAndExcludedStatus(String testId, List statusIdList) - throws LIMSRuntimeException; + List getAllAnalysisByTestAndExcludedStatus(String testId, List statusIdList) + throws LIMSRuntimeException; - List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException; + List getAllAnalysisByTestSectionAndStatus(String testSectionId, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException; - List getAllAnalysisByTestSectionAndExcludedStatus( - String testSectionId, List statusIdList) throws LIMSRuntimeException; + List getAllAnalysisByTestSectionAndExcludedStatus(String testSectionId, List statusIdList) + throws LIMSRuntimeException; - List getAnalysesBySampleItem(SampleItem sampleItem) throws LIMSRuntimeException; + List getAnalysesBySampleItem(SampleItem sampleItem) throws LIMSRuntimeException; - List getAnalysesBySampleItemsExcludingByStatusIds( - SampleItem sampleItem, Set statusIds) throws LIMSRuntimeException; + List getAnalysesBySampleItemsExcludingByStatusIds(SampleItem sampleItem, Set statusIds) + throws LIMSRuntimeException; - List getAnalysesBySampleStatusId(String statusId) throws LIMSRuntimeException; + List getAnalysesBySampleStatusId(String statusId) throws LIMSRuntimeException; - List getAnalysesBySampleStatusIdExcludingByStatusId( - String statusId, Set statusIds) throws LIMSRuntimeException; + List getAnalysesBySampleStatusIdExcludingByStatusId(String statusId, Set statusIds) + throws LIMSRuntimeException; - List getAnalysesReadyToBeReported() throws LIMSRuntimeException; + List getAnalysesReadyToBeReported() throws LIMSRuntimeException; - List getAllChildAnalysesByResult(Result result) throws LIMSRuntimeException; + List getAllChildAnalysesByResult(Result result) throws LIMSRuntimeException; - List getMaxRevisionAnalysesReadyToBeReported() throws LIMSRuntimeException; + List getMaxRevisionAnalysesReadyToBeReported() throws LIMSRuntimeException; - List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers) - throws LIMSRuntimeException; + List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers) + throws LIMSRuntimeException; - List getAnalysesAlreadyReportedBySample(Sample sample) throws LIMSRuntimeException; + List getAnalysesAlreadyReportedBySample(Sample sample) throws LIMSRuntimeException; - List getMaxRevisionAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException; + List getMaxRevisionAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException; - List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) - throws LIMSRuntimeException; + List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) throws LIMSRuntimeException; - List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) - throws LIMSRuntimeException; + List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException; - List getRevisionHistoryOfAnalysesBySampleAndTest( - SampleItem sampleItem, Test test, boolean includeLatestRevision) throws LIMSRuntimeException; + List getRevisionHistoryOfAnalysesBySampleAndTest(SampleItem sampleItem, Test test, + boolean includeLatestRevision) throws LIMSRuntimeException; - List getAllMaxRevisionAnalysesPerTest(Test test) throws LIMSRuntimeException; + List getAllMaxRevisionAnalysesPerTest(Test test) throws LIMSRuntimeException; - List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) - throws LIMSRuntimeException; + List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) throws LIMSRuntimeException; - List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) - throws LIMSRuntimeException; + List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) + throws LIMSRuntimeException; - Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) throws LIMSRuntimeException; + Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) throws LIMSRuntimeException; - void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) throws LIMSRuntimeException; + void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) throws LIMSRuntimeException; - List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) - throws LIMSRuntimeException; + List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException; - List getAnalysesForStatusId(String statusId) throws LIMSRuntimeException; + List getAnalysesForStatusId(String statusId) throws LIMSRuntimeException; - List getAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) - throws LIMSRuntimeException; + List getAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) + throws LIMSRuntimeException; - List getAnalysisStartedOn(Date collectionDate) throws LIMSRuntimeException; + List getAnalysisStartedOn(Date collectionDate) throws LIMSRuntimeException; - List getAnalysisCollectedOnExcludedByStatusId( - Date collectionDate, Set statusIds) throws LIMSRuntimeException; + List getAnalysisCollectedOnExcludedByStatusId(Date collectionDate, Set statusIds) + throws LIMSRuntimeException; - List getAnalysisCollectedOn(Date collectionDate) throws LIMSRuntimeException; + List getAnalysisCollectedOn(Date collectionDate) throws LIMSRuntimeException; - List getAnalysesBySampleId(String id) throws LIMSRuntimeException; + List getAnalysesBySampleId(String id) throws LIMSRuntimeException; - List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) - throws LIMSRuntimeException; + List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) + throws LIMSRuntimeException; - List getAnalysisBySampleAndTestIds(String sampleKey, List testIds); + List getAnalysisBySampleAndTestIds(String sampleKey, List testIds); - List getAnalysesBySampleIdTestIdAndStatusId( - List sampleIdList, List testIdList, List statusIdList); + List getAnalysesBySampleIdTestIdAndStatusId(List sampleIdList, List testIdList, + List statusIdList); - // Analysis getPatientPreviousAnalysisForTestName(Patient patient, Sample currentSample, String - // testName); + // Analysis getPatientPreviousAnalysisForTestName(Patient patient, Sample + // currentSample, String + // testName); - List getAnalysisByTestSectionAndCompletedDateRange( - String sectionID, Date lowDate, Date highDate) throws LIMSRuntimeException; + List getAnalysisByTestSectionAndCompletedDateRange(String sectionID, Date lowDate, Date highDate) + throws LIMSRuntimeException; - List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) - throws LIMSRuntimeException; + List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) throws LIMSRuntimeException; - List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange( - Date lowDate, Date highDate, String testId, List testSectionIds) - throws LIMSRuntimeException; + List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange(Date lowDate, Date highDate, String testId, + List testSectionIds) throws LIMSRuntimeException; - List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) - throws LIMSRuntimeException; + List getAllAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) throws LIMSRuntimeException; - List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID) - throws LIMSRuntimeException; + List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID) + throws LIMSRuntimeException; - List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) - throws LIMSRuntimeException; + List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) throws LIMSRuntimeException; - List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate) - throws LIMSRuntimeException; + List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate) throws LIMSRuntimeException; - List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) - throws LIMSRuntimeException; + List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) throws LIMSRuntimeException; - List getAnalysesBySampleIdAndStatusId(String id, Set analysisStatusIds) - throws LIMSRuntimeException; + List getAnalysesBySampleIdAndStatusId(String id, Set analysisStatusIds) + throws LIMSRuntimeException; - List getAnalysisByTestNamesAndCompletedDateRange( - List testNames, Date lowDate, Date highDate) throws LIMSRuntimeException; + List getAnalysisByTestNamesAndCompletedDateRange(List testNames, Date lowDate, Date highDate) + throws LIMSRuntimeException; - List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId) - throws LIMSRuntimeException; + List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId) + throws LIMSRuntimeException; - List getAnalysisByTestDescriptionAndCompletedDateRange( - List descriptions, Date sqlDayOne, Date sqlDayTwo) throws LIMSRuntimeException; + List getAnalysisByTestDescriptionAndCompletedDateRange(List descriptions, Date sqlDayOne, + Date sqlDayTwo) throws LIMSRuntimeException; - Analysis getAnalysisById(String analysisId) throws LIMSRuntimeException; + Analysis getAnalysisById(String analysisId) throws LIMSRuntimeException; - List getAllAnalysisByTestsAndStatus( - List testIds, List analysisStatusList, List sampleStatusList); + List getAllAnalysisByTestsAndStatus(List testIds, List analysisStatusList, + List sampleStatusList); - @Override - List get(List value); + @Override + List get(List value); - List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List testIdList, - List analysisStatusList, - List sampleStatusList, - Date lowDate, - Date highDate); + List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List testIdList, + List analysisStatusList, List sampleStatusList, Date lowDate, Date highDate); - List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List nfsTestIdList, List statusList, Date lowDate, Date highDate); + List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List nfsTestIdList, + List statusList, Date lowDate, Date highDate); - List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList); + List getPageAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList); - int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList); - // void updateData(Analysis analysis, boolean skipAuditTrail) throws LIMSRuntimeException; + int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList); + // void updateData(Analysis analysis, boolean skipAuditTrail) throws + // LIMSRuntimeException; - List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException; + List getPageAnalysisByTestSectionAndStatus(String testSectionId, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException; - List getPageAnalysisAtAccessionNumberAndStatus( - String accessionNumber, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException; + List getPageAnalysisAtAccessionNumberAndStatus(String accessionNumber, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException; - int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList); + int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList); - int getCountAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber); + int getCountAnalysisByStatusFromAccession(List analysisStatusList, List sampleStatusList, + String accessionNumber); - List getPageAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber); + List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber); - List getPageAnalysisByStatusFromAccession( - List analysisStatusList, - List sampleStatusList, - String accessionNumber, - String upperRangeAccessionNumber, - boolean doRange, - boolean finished); + List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber, String upperRangeAccessionNumber, boolean doRange, + boolean finished); - List getAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate); + List getAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate); - List getAnalysesByPriorityAndStatusId( - OrderPriority priority, List analysisStatusIds); + List getAnalysesByPriorityAndStatusId(OrderPriority priority, List analysisStatusIds); - List getStudyAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate); + List getStudyAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate); - List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) - throws LIMSRuntimeException; + List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) throws LIMSRuntimeException; - List getAnalysesResultEnteredOnExcludedByStatusId( - Date completedDate, Set statusIds) throws LIMSRuntimeException; + List getAnalysesResultEnteredOnExcludedByStatusId(Date completedDate, Set statusIds) + throws LIMSRuntimeException; - int getCountOfAnalysesForStatusIds(List statusIdList); + int getCountOfAnalysesForStatusIds(List statusIdList); - int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds); + int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds); - int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds); + int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds); - int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds); + int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds); } diff --git a/src/main/java/org/openelisglobal/analysis/daoimpl/AnalysisDAOImpl.java b/src/main/java/org/openelisglobal/analysis/daoimpl/AnalysisDAOImpl.java index 8957098736..bb3ce2df37 100644 --- a/src/main/java/org/openelisglobal/analysis/daoimpl/AnalysisDAOImpl.java +++ b/src/main/java/org/openelisglobal/analysis/daoimpl/AnalysisDAOImpl.java @@ -53,1986 +53,1742 @@ @Transactional public class AnalysisDAOImpl extends BaseDAOImpl implements AnalysisDAO { - public AnalysisDAOImpl() { - super(Analysis.class); - } - - @Override - @Transactional(readOnly = true) - public void getData(Analysis analysis) throws LIMSRuntimeException { - - try { - Analysis analysisClone = - entityManager.unwrap(Session.class).get(Analysis.class, analysis.getId()); - if (analysisClone != null) { - PropertyUtils.copyProperties(analysis, analysisClone); - } else { - analysis.setId(null); - } - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getData()", e); - } - } - - public Analysis readAnalysis(String idString) { - Analysis analysis = null; - try { - analysis = entityManager.unwrap(Session.class).get(Analysis.class, idString); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis readAnalysis()", e); - } - - return analysis; - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestAndStatus(String testId, List statusIdList) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where a.test = :testId and a.statusId IN (:statusIdList) order by" - + " a.sampleItem.sample.accessionNumber"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testId", Integer.parseInt(testId)); - query.setParameterList("statusIdList", statusIdList); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestAndStatuses()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatus( - List testIdList, List statusIdList) throws LIMSRuntimeException { - List testList = new ArrayList<>(); - try { - String sql = - "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:statusIdList) order" - + " by a.sampleItem.sample.accessionNumber"; - - for (String testId : testIdList) { - testList.add(Integer.parseInt(testId)); - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("testList", testList); - query.setParameterList("statusIdList", statusIdList); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestsAndStatuses()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List testIdList, List statusIdList, Date lowDate, Date highDate) - throws LIMSRuntimeException { - List testList = new ArrayList<>(); - try { - String sql = - "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:statusIdList) and" - + " a.completedDate BETWEEN :lowDate AND :highDate order by" - + " a.sampleItem.sample.accessionNumber"; - - for (String testId : testIdList) { - testList.add(Integer.parseInt(testId)); - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("testList", testList); - query.setParameterList("statusIdList", statusIdList); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAllAnalysisByTestsAndStatusAndCompletedDateRange()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestAndExcludedStatus( - String testId, List statusIdList) throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where a.test = :testId and a.statusId not IN (:statusIdList) order by" - + " a.sampleItem.sample.accessionNumber"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testId", Integer.parseInt(testId)); - query.setParameterList("statusIdList", statusIdList); - return query.list(); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAllAnalysisByTestAndExcludedStatuses()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException { - if (testSectionId == null) { - return new ArrayList<>(); - } - try { - String sql = - "from Analysis a where a.testSection.id = :testSectionId and a.statusId IN" - + " (:statusIdList) order by a.id"; - - if (sortedByDateAndAccession) { - // sql += " order by a.sampleItem.sample.receivedTimestamp asc, - // a.sampleItem.sample.accessionNumber"; - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("statusIdList", statusIdList); - return query.list(); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAllAnalysisByTestSectionAndStatuses()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a " - + " where a.testSection.id = :testSectionId " - + " and a.statusId IN (:statusIdList) " - + " order by a.sampleItem.sample.accessionNumber "; - - if (sortedByDateAndAccession) { - // sql += " order by a.sampleItem.sample.receivedTimestamp asc, - // a.sampleItem.sample.accessionNumber"; - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("statusIdList", statusIdList); - // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getValidationPageSize()); - - return query.list(); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAllAnalysisByTestSectionAndStatuses()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getPageAnalysisAtAccessionNumberAndStatus( - String accessionNumber, List statusIdList, boolean sortedByDateAndAccession) - throws LIMSRuntimeException { - - String hql = - "from Analysis a " // - + " where a.sampleItem.sample.accessionNumber >= :accessionNumber" // - + " and length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber) " // - + " and a.statusId IN (:statusIdList) " // - + " order by a.sampleItem.sample.accessionNumber"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); - - query.setParameter("accessionNumber", accessionNumber); - query.setParameterList("statusIdList", statusIdList); - // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getValidationPageSize()); - - return query.list(); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getPageAnalysisAtAccessionNumberAndStatus()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndExcludedStatus( - String testSectionId, List statusIdList) throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where a.testSection.id = :testSectionId and a.statusId NOT IN" - + " (:statusIdList) order by a.sampleItem.sample.receivedTimestamp asc," - + " a.sampleItem.sample.accessionNumber "; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("statusIdList", statusIdList); - return query.list(); - } catch (RuntimeException e) { + public AnalysisDAOImpl() { + super(Analysis.class); + } + + @Override + @Transactional(readOnly = true) + public void getData(Analysis analysis) throws LIMSRuntimeException { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAllAnalysisByTestSectionAndExcludedStatuses()", e); + try { + Analysis analysisClone = entityManager.unwrap(Session.class).get(Analysis.class, analysis.getId()); + if (analysisClone != null) { + PropertyUtils.copyProperties(analysis, analysisClone); + } else { + analysis.setId(null); + } + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getData()", e); + } } - } - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItem(SampleItem sampleItem) throws LIMSRuntimeException { - List list = null; - try { - String sql = "from Analysis a where a.sampleItem.id = :sampleItemId"; + public Analysis readAnalysis(String idString) { + Analysis analysis = null; + try { + analysis = entityManager.unwrap(Session.class).get(Analysis.class, idString); + } catch (RuntimeException e) { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleItemId", Integer.parseInt(sampleItem.getId())); + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis readAnalysis()", e); + } - list = query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getAnalysesBySampleItem()", e); + return analysis; } - return list; - } + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestAndStatus(String testId, List statusIdList) + throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.test = :testId and a.statusId IN (:statusIdList) order by" + + " a.sampleItem.sample.accessionNumber"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testId", Integer.parseInt(testId)); + query.setParameterList("statusIdList", statusIdList); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestAndStatuses()", e); + } + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatus(List testIdList, List statusIdList) + throws LIMSRuntimeException { + List testList = new ArrayList<>(); + try { + String sql = "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:statusIdList) order" + + " by a.sampleItem.sample.accessionNumber"; + + for (String testId : testIdList) { + testList.add(Integer.parseInt(testId)); + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("testList", testList); + query.setParameterList("statusIdList", statusIdList); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestsAndStatuses()", e); + } + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List testIdList, + List statusIdList, Date lowDate, Date highDate) throws LIMSRuntimeException { + List testList = new ArrayList<>(); + try { + String sql = "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:statusIdList) and" + + " a.completedDate BETWEEN :lowDate AND :highDate order by" + + " a.sampleItem.sample.accessionNumber"; + + for (String testId : testIdList) { + testList.add(Integer.parseInt(testId)); + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("testList", testList); + query.setParameterList("statusIdList", statusIdList); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestsAndStatusAndCompletedDateRange()", + e); + } + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestAndExcludedStatus(String testId, List statusIdList) + throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.test = :testId and a.statusId not IN (:statusIdList) order by" + + " a.sampleItem.sample.accessionNumber"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testId", Integer.parseInt(testId)); + query.setParameterList("statusIdList", statusIdList); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestAndExcludedStatuses()", e); + } + } - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItemsExcludingByStatusIds( - SampleItem sampleItem, Set statusIds) throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysesBySampleItem(sampleItem); + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndStatus(String testSectionId, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException { + if (testSectionId == null) { + return new ArrayList<>(); + } + try { + String sql = "from Analysis a where a.testSection.id = :testSectionId and a.statusId IN" + + " (:statusIdList) order by a.id"; + + if (sortedByDateAndAccession) { + // sql += " order by a.sampleItem.sample.receivedTimestamp asc, + // a.sampleItem.sample.accessionNumber"; + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("statusIdList", statusIdList); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestSectionAndStatuses()", e); + } } - List analysisList = null; + @Override + @Transactional(readOnly = true) + public List getPageAnalysisByTestSectionAndStatus(String testSectionId, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException { + try { + String sql = "from Analysis a " + " where a.testSection.id = :testSectionId " + + " and a.statusId IN (:statusIdList) " + " order by a.sampleItem.sample.accessionNumber "; - try { - String sql = - "from Analysis a where a.sampleItem.id = :sampleItemId and a.statusId not in (" - + " :statusList )"; + if (sortedByDateAndAccession) { + // sql += " order by a.sampleItem.sample.receivedTimestamp asc, + // a.sampleItem.sample.accessionNumber"; + } - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleItemId", Integer.parseInt(sampleItem.getId())); - query.setParameterList("statusList", statusIds); + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - analysisList = query.list(); - } catch (RuntimeException e) { + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("statusIdList", statusIdList); + // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getValidationPageSize()); - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAnalysesBySampleItemsExcludingByStatusIds()", e); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestSectionAndStatuses()", e); + } } - return analysisList; - } + @Override + @Transactional(readOnly = true) + public List getPageAnalysisAtAccessionNumberAndStatus(String accessionNumber, List statusIdList, + boolean sortedByDateAndAccession) throws LIMSRuntimeException { + + String hql = "from Analysis a " // + + " where a.sampleItem.sample.accessionNumber >= :accessionNumber" // + + " and length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber) " // + + " and a.statusId IN (:statusIdList) " // + + " order by a.sampleItem.sample.accessionNumber"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); + + query.setParameter("accessionNumber", accessionNumber); + query.setParameterList("statusIdList", statusIdList); + // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getValidationPageSize()); - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleStatusIdExcludingByStatusId( - String statusId, Set statusIds) throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysesBySampleStatusId(statusId); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getPageAnalysisAtAccessionNumberAndStatus()", e); + } + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndExcludedStatus(String testSectionId, List statusIdList) + throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.testSection.id = :testSectionId and a.statusId NOT IN" + + " (:statusIdList) order by a.sampleItem.sample.receivedTimestamp asc," + + " a.sampleItem.sample.accessionNumber "; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("statusIdList", statusIdList); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllAnalysisByTestSectionAndExcludedStatuses()", e); + } } - String sql = - "from Analysis a where a.sampleItem.sample.statusId = :sampleStatus and a.statusId not in" - + " (:excludedStatusIds)"; + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItem(SampleItem sampleItem) throws LIMSRuntimeException { + List list = null; + try { + String sql = "from Analysis a where a.sampleItem.id = :sampleItemId"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleStatus", Integer.parseInt(statusId)); - query.setParameterList("excludedStatusIds", statusIds); + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleItemId", Integer.parseInt(sampleItem.getId())); - List analysisList = query.list(); - return analysisList; + list = query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAnalysesBySampleItem()", e); + } - } catch (HibernateException e) { - handleException(e, "getAnalysesBySampleStatusIdExcludingByStatusId"); + return list; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItemsExcludingByStatusIds(SampleItem sampleItem, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysesBySampleItem(sampleItem); + } - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleStatusId(String statusId) throws LIMSRuntimeException { - List analysisList = null; + List analysisList = null; - try { - String sql = "from Analysis a where a.sampleItem.sample.statusId = :sampleStatusId"; + try { + String sql = "from Analysis a where a.sampleItem.id = :sampleItemId and a.statusId not in (" + + " :statusList )"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleStatusId", Integer.parseInt(statusId)); + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleItemId", Integer.parseInt(sampleItem.getId())); + query.setParameterList("statusList", statusIds); - analysisList = query.list(); - } catch (RuntimeException e) { + analysisList = query.list(); + } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getAnalysesBySampleItemsExcludingByStatusIds()", e); + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAnalysesBySampleItemsExcludingByStatusIds()", e); + } + + return analysisList; } - - return analysisList; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) - throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysesBySampleId(id); - } - - String sql = - "from Analysis a where a.sampleItem.sample.id = :sampleId and a.statusId not in (" - + " :excludedIds)"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleId", Integer.parseInt(id)); - query.setParameterList("excludedIds", statusIds); - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysesBySampleIdExcludedByStatusId"); - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdAndStatusId(String id, Set statusIds) - throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysesBySampleId(id); - } - - String sql = - "from Analysis a where a.sampleItem.sample.id = :sampleId and a.statusId in ( :statusIds)"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleId", Integer.parseInt(id)); - query.setParameterList("statusIds", statusIds); - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysesBySampleIdAndStatusId"); - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesByPriorityAndStatusId( - OrderPriority priority, List statusIds) throws LIMSRuntimeException { - String sql = - "from Analysis a where a.sampleItem.sample.priority = :oderpriority and a.statusId in (" - + " :statusIds)"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("oderpriority", priority.name()); - query.setParameterList("statusIds", statusIds); - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysesBySampleIdAndStatusId"); - } - - return null; - } - - /** - * bugzilla 1993 (part of 1942) getAnalysesReadyToBeReported() - returns the tests that should be - * updated with a printed date of today's date (see ResultsReport) - */ - @Override - @Transactional(readOnly = true) - public List getAnalysesReadyToBeReported() throws LIMSRuntimeException { - try { - List analysisStatusesToInclude = new ArrayList<>(); - analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusReleased()); - - List sampleStatusesToInclude = new ArrayList<>(); - sampleStatusesToInclude.add( - SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); - sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); - - String sql = - "select distinct anal.id\n" - + " from\n" - + " sample samp,\n" - + " test_analyte ta,\n" - + " analysis anal,\n" - + " sample_item sampitem,\n" - + " test test,\n" - + " result res\n" - + "\n" - + " where\n" - + " ta.test_id = test.id and\n" - + " ta.analyte_id=res.analyte_id and\n" - + " anal.id = res.analysis_id and\n" - + " anal.test_id = test.id and\n" - + " anal.sampitem_id = sampitem. id and\n" - + " sampitem.samp_id = samp.id\n" - + " and res.is_reportable = 'Y'\n" - + " and anal.is_reportable = 'Y'\n" - + " and anal.printed_date is null\n" - + " and anal.status in (:analysisStatusesToInclude)\n" - + " and samp.status in(:sampleStatusesToInclude)\n" - + " --bugzilla 2028 - there is corresponding sql in main_report.jrxml and" - + " test_results.jrxml to make sure we exclude the samples for which tests qa events" - + " are not completed\n" - + " --isQaEventsCompleted is 'Y' or 'N'\n" - + " --------------if there are no qa events for this test then" - + " isQaEventsCompleted = 'Y'\n" - + " and 'Y' = case when (select count(*) from analysis_qaevent aq where" - + " aq.analysis_id = anal.id)= 0 then 'Y'\n" - + " --if there are no holdable qa events for this test then " - + " isQaEventsCompleted = 'Y'\n" - + " when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --if there the holdable qa events for this test are" - + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" - + " when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --else isQaEventsCompleted = 'N'\n" - + " else 'N'end"; - return entityManager - .unwrap(Session.class) - .createQuery(sql, Analysis.class) - .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) - .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude) - .list(); - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in getAnalysesReadyToBeReported()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllChildAnalysesByResult(Result result) throws LIMSRuntimeException { - try { - String sql = "from Analysis a where a.parentResult = :param and a.status NOT IN (:param2)"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", result.getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param2", statusesToExclude); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getallChildAnalysesByResult()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesBySample(SampleItem sampleItem) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem.id = :param " - + "and a.status NOT IN (:param2) " - + "order by a.test.id, a.revision desc"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", sampleItem.getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param2", statusesToExclude); - return query.list(); - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); - } - } - - // bugzilla 2300 (separate method for sample tracking) - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem.id = :param " - + "order by a.test.id, a.revision desc"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", sampleItem.getId()); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) NOT IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem.id = :param " - + "and a.status NOT IN (:param2) " - + "order by a.test.id, a.revision desc"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", sampleItem.getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param2", statusesToExclude); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getRevisionHistoryOfAnalysesBySample()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getRevisionHistoryOfAnalysesBySampleAndTest( - SampleItem sampleItem, Test test, boolean includeLatestRevision) throws LIMSRuntimeException { - try { - String sql = ""; - if (includeLatestRevision) { - sql = - "from Analysis a " - + "where a.sampleItem.id = :param " - + "and a.status NOT IN (:param3) " - + "and a.test.id = :param2 " - + "order by a.test.id, a.revision desc"; - } else { - sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) NOT IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem.id = :param " - + "and a.status NOT IN (:param3) " - + "and a.test.id = :param2 " - + "order by a.test.id, a.revision desc"; - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", sampleItem.getId()); - query.setParameter("param2", test.getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param3", statusesToExclude); - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getRevisionHistoryOfAnalysesBySample()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllMaxRevisionAnalysesPerTest(Test test) throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where (a.sampleItem.id, a.revision) IN " - + "(select b.sampleItem.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id) " - + "and a.test = :param " - + "and a.status NOT IN (:param2) " - + "order by a.sampleItem.sample.accessionNumber"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", test.getId()); - - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param2", statusesToExclude); - - return query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getAllMaxRevisionAnalysesPerTest()", e); - } - } - - // bugzilla 2227, 2258 - @Override - @Transactional - public List getMaxRevisionAnalysesReadyToBeReported() throws LIMSRuntimeException { - try { - List analysisStatusesToInclude = new ArrayList<>(); - analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusReleased()); - - List sampleStatusesToInclude = new ArrayList<>(); - sampleStatusesToInclude.add( - SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); - sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); - - String sql = - "select distinct anal.id\n" - + " from\n" - + " sample samp,\n" - + " test_analyte ta,\n" - + " analysis anal,\n" - + " sample_item sampitem,\n" - + " test test,\n" - + " result res\n" - + "\n" - + " where\n" - + " (\n" - + " (\n" - + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" - + " )IN(\n" - + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" - + " from\n" - + " analysis anal2\n" - + " group by\n" - + " anal2.SAMPITEM_ID ,\n" - + " anal2.TEST_ID\n" - + " )\n" - + " ) and\n" - + " ta.test_id = test.id and\n" - + " ta.analyte_id=res.analyte_id and\n" - + " anal.id = res.analysis_id and\n" - + " anal.test_id = test.id and\n" - + " anal.sampitem_id = sampitem. id and\n" - + " sampitem.samp_id = samp.id\n" - + " and res.is_reportable = 'Y'\n" - + " and anal.is_reportable = 'Y'\n" - + " and anal.printed_date is null\n" - + " and anal.status in (:analysisStatusesToInclude)\n" - + " and samp.status in(:sampleStatusesToInclude)\n" - + " --bugzilla 2028 make sure we exclude the samples for which tests qa" - + " events are not completed\n" - + " --isQaEventsCompleted is 'Y' or 'N'\n" - + " --------------if there are no qa events for this test then" - + " isQaEventsCompleted = 'Y'\n" - + " and 'Y' = case when (select count(*) from analysis_qaevent aq where" - + " aq.analysis_id = anal.id)= 0 then 'Y'\n" - + " --if there are no holdable qa events for this test then " - + " isQaEventsCompleted = 'Y'\n" - + " when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --if there the holdable qa events for this test are" - + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" - + " when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --else isQaEventsCompleted = 'N'\n" - + " else 'N'\n" - + " end"; - return entityManager - .unwrap(Session.class) - .createNativeQuery(sql, Analysis.class) - .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) - .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude) - .list(); - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getMaxRevisionAnalysesReadyToBeReported()", e); - } - } - - // bugzilla 1900 - @Override - @Transactional - public List getMaxRevisionAnalysesReadyForReportPreviewBySample( - List accessionNumbers) throws LIMSRuntimeException { - List list = new Vector<>(); - try { - List analysisStatusesToInclude = new ArrayList<>(); - // see question in 1900 should this be released or results completed - // status? - // answer: results completed - analysisStatusesToInclude.add( - SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); - - List sampleStatusesToInclude = new ArrayList<>(); - sampleStatusesToInclude.add( - SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); - // see question in 1900 - should this be included? Yes - sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); - - if (accessionNumbers != null && accessionNumbers.size() > 0) { - String sql = - "select distinct anal.id\n" - + " from\n" - + " sample samp,\n" - + " test_analyte ta,\n" - + " analysis anal,\n" - + " sample_item sampitem,\n" - + " test test,\n" - + " result res\n" - + "\n" - + " where\n" - + " (\n" - + " (\n" - + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" - + " )IN(\n" - + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" - + " from\n" - + " analysis anal2\n" - + " group by\n" - + " anal2.SAMPITEM_ID ,\n" - + " anal2.TEST_ID\n" - + " )\n" - + " ) and\n" - + " ta.test_id = test.id and\n" - + " ta.analyte_id=res.analyte_id and\n" - + " anal.id = res.analysis_id and\n" - + " anal.test_id = test.id and\n" - + " anal.sampitem_id = sampitem. id and\n" - + " sampitem.samp_id = samp.id\n" - + " and res.is_reportable = 'Y'\n" - + " and anal.is_reportable = 'Y'\n" - + " and anal.printed_date is null\n" - + " and anal.status in (:analysisStatusesToInclude)\n" - + " and samp.status in(:sampleStatusesToInclude)\n" - + " and samp.accession_number in(:samplesToInclude)\n" - + " --bugzilla 2509 removed exclusion of holdable not completed qa" - + " events\n" - + " --bugzilla 2028 make sure we exclude the samples for which tests qa" - + " events are not completed\n" - + " --isQaEventsCompleted is 'Y' or 'N'\n" - + " --------------if there are no qa events for this test then" - + " isQaEventsCompleted = 'Y'\n" - + " --and 'Y' = case when (select count(*) from analysis_qaevent aq" - + " where aq.analysis_id = anal.id)= 0 then 'Y'\n" - + " --if there are no holdable qa events for this test then " - + " isQaEventsCompleted = 'Y'\n" - + " --when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --if there the holdable qa events for this test are" - + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" - + " --when (select count(*) from analysis_qaevent aq," - + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" - + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" - + " --else isQaEventsCompleted = 'N'\n" - + " --else 'N'\n" - + " --end"; - list = - entityManager - .unwrap(Session.class) - .createNativeQuery(sql) - .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) - .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude) - .setParameterList("samplesToInclude", accessionNumbers) - .list(); - } - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in getMaxRevisionAnalysesReadyForReportPreviewBySample()", e); - } - return list; - } - - // bugzilla 1856 - @Override - @Transactional - public List getAnalysesAlreadyReportedBySample(Sample sample) - throws LIMSRuntimeException { - try { - String sql = - "select distinct anal.id\n" - + " from\n" - + " sample samp,\n" - + " test_analyte ta,\n" - + " analysis anal,\n" - + " sample_item sampitem,\n" - + " test test,\n" - + " result res\n" - + "\n" - + " where\n" - + " (\n" - + " (\n" - + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" - + " )IN(\n" - + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" - + " from\n" - + " analysis anal2\n" - + " group by\n" - + " anal2.SAMPITEM_ID ,\n" - + " anal2.TEST_ID\n" - + " )\n" - + " ) and\n" - + " samp.id = :sampleId and\n" - + " ta.test_id = test.id and\n" - + " ta.analyte_id=res.analyte_id and\n" - + " anal.id = res.analysis_id and\n" - + " anal.test_id = test.id and\n" - + " anal.sampitem_id = sampitem. id and\n" - + " sampitem.samp_id = samp.id\n" - + " and anal.printed_date is not null"; - return entityManager - .unwrap(Session.class) - .createNativeQuery(sql) - .setParameter("sampleId", sample.getId()) - .list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in getAnalysesAlreadyReportedBySample()", e); - } - } - - // bugzilla 2264 - @Override - @Transactional - public List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) - throws LIMSRuntimeException { - try { - List analysisStatusesToInclude = new ArrayList<>(); - analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); - // bugzilla 2264 per Nancy add results completed status to pending - // tests - analysisStatusesToInclude.add( - SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); - - String sql = - "select\n" - + " distinct anal.id\n" - + " from\n" - + " sample_item sampitem,\n" - + " sample samp,\n" - + " analysis anal,\n" - + " test test\n" - + "\n" - + " where\n" - + " (\n" - + " (\n" - + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" - + " )IN(\n" - + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" - + " from\n" - + " analysis anal2\n" - + " group by\n" - + " anal2.SAMPITEM_ID ,\n" - + " anal2.TEST_ID\n" - + " )\n" - + " ) and\n" - + " samp.id = :sampleId\n" - + " and sampitem.samp_id = samp.id\n" - + " and anal.sampitem_id = sampitem. id\n" - + " and anal.test_id = test.id\n" - + " and\n" - + "\n" - + " (select count(*)\n" - + " from test_analyte t_a\n" - + " where t_a.test_id = test.id and\n" - + " (t_a.id) in (\n" - + " select ta.id\n" - + " from test_analyte ta,\n" - + " analysis anal2,\n" - + " sample_item sampitem,\n" - + " sample samp,\n" - + " test test\n" - + " where\n" - + " samp.id = :sampleId and\n" - + " sampitem.samp_id = samp.id and\n" - + " anal2.sampitem_id = sampitem. id and\n" - + " anal2.test_id = test.id and\n" - + " ta.test_id = test.id and\n" - + " ta.is_reportable = 'Y' and\n" - + " anal2.is_reportable = 'Y' and\n" - + " anal2.printed_date is null and\n" - + " anal.id = anal2.id and\n" - + " anal2.status in (:analysisStatusesToInclude)\n" - + " )\n" - + " ) > 0"; - return entityManager - .unwrap(Session.class) - .createNativeQuery(sql) - .setParameter("sampleId", sample.getId()) - .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) - .list(); - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getMaxRevisionPendingAnalysesReadyToBeReportedBySample()", e); - } - } - - // bugzilla 1900 - @SuppressWarnings("unchecked") - @Override - @Transactional(readOnly = true) - public List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) - throws LIMSRuntimeException { - List list = new Vector<>(); - - try { - - List analysisStatusesToInclude = new ArrayList<>(); - analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); - // see question in 1900 do we need to include this? - // Answer NO - // analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); - - list = - entityManager - .unwrap(Session.class) - .getNamedQuery("analysis.getMaxRevisionPendingAnalysesReadyToBeReportedBySample") - .setParameter("sampleId", sample.getId()) - .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) - .list(); - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in getMaxRevisionPendingAnalysesReadyForReportPreviewBySample()", e); - } - - return list; - } - - @Override - @Transactional(readOnly = true) - public Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) - throws LIMSRuntimeException { - Analysis previousAnalysis = null; - try { - // Use an expression to read in the Analysis whose - // revision is 1 less than the analysis passed in - - String sql = - "from Analysis a where a.revision = :param and a.sampleItem = :param2 and a.test =" - + " :param3 and a.status NOT IN (:param4)"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - - String revisionString = analysis.getRevision(); - int revision = 0; - if (!StringUtil.isNullorNill(revisionString)) { - try { - revision = Integer.parseInt(revisionString); - } catch (NumberFormatException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in getPreviousAnalysisForAmendedAnalysis()", e); - } - } - - query.setParameter("param", String.valueOf((revision - 1))); - query.setParameter("param2", analysis.getSampleItem()); - query.setParameter("param3", analysis.getTest()); - - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param4", statusesToExclude); - List list = query.list(); - if ((list != null) && !list.isEmpty()) { - previousAnalysis = list.get(0); - } - - } catch (RuntimeException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Exception occurred in getPreviousAnalysisForAmendedAnalysis", e); - } - return previousAnalysis; - } - - @Override - @Transactional(readOnly = true) - public void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) throws LIMSRuntimeException { - - try { - Analysis anal = null; - String sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem = :param " - + "and a.status NOT IN (:param3) " - + "and a.test = :param2"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", analysis.getSampleItem().getId()); - query.setParameter("param2", analysis.getTest().getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param3", statusesToExclude); - anal = query.uniqueResult(); - - if (anal != null) { - PropertyUtils.copyProperties(analysis, anal); - } else { - analysis.setId(null); - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - - LogEvent.logError(e); - throw new LIMSRuntimeException( - "Error in Analysis getMaxRevisionAnalysisBySampleAndTest()", e); - } - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) - throws LIMSRuntimeException { - - List list = new Vector<>(); - try { - - String sql = - "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " - + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " - + "group by b.sampleItem.id, b.test.id) " - + "and a.sampleItem.id = :param " - + "and a.status NOT IN (:param2) " - + "and a.parentAnalysis is null " - + "order by a.test.id, a.revision desc"; - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("param", sampleItem.getId()); - List statusesToExclude = new ArrayList<>(); - statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); - query.setParameterList("param2", statusesToExclude); - list = query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleStatusIdExcludingByStatusId(String statusId, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysesBySampleStatusId(statusId); + } + + String sql = "from Analysis a where a.sampleItem.sample.statusId = :sampleStatus and a.statusId not in" + + " (:excludedStatusIds)"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleStatus", Integer.parseInt(statusId)); + query.setParameterList("excludedStatusIds", statusIds); + + List analysisList = query.list(); + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getAnalysesBySampleStatusIdExcludingByStatusId"); + } + + return null; } - return list; - } + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleStatusId(String statusId) throws LIMSRuntimeException { + List analysisList = null; - @Override - @Transactional(readOnly = true) - public List getAnalysesForStatusId(String statusId) throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.sampleItem.sample.statusId = :sampleStatusId"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleStatusId", Integer.parseInt(statusId)); - List list = null; - - try { - String sql = "from Analysis a where a.statusId = :statusId"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("statusId", Integer.parseInt(statusId)); + analysisList = query.list(); + } catch (RuntimeException e) { - list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisForStatusId"); + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAnalysesBySampleItemsExcludingByStatusIds()", e); + } + + return analysisList; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysesBySampleId(id); + } + + String sql = "from Analysis a where a.sampleItem.sample.id = :sampleId and a.statusId not in (" + + " :excludedIds)"; - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOnExcludedByStatusId( - Date collectionDate, Set statusIds) throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysisStartedOn(collectionDate); + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleId", Integer.parseInt(id)); + query.setParameterList("excludedIds", statusIds); + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysesBySampleIdExcludedByStatusId"); + } + + return null; } - String sql = - "from Analysis a where a.startedDate = :startedDate and a.statusId not in ( :statusList )"; + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdAndStatusId(String id, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysesBySampleId(id); + } - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("startedDate", collectionDate); - query.setParameterList("statusList", statusIds); + String sql = "from Analysis a where a.sampleItem.sample.id = :sampleId and a.statusId in ( :statusIds)"; - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleId", Integer.parseInt(id)); + query.setParameterList("statusIds", statusIds); + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysesBySampleIdAndStatusId"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesByPriorityAndStatusId(OrderPriority priority, List statusIds) + throws LIMSRuntimeException { + String sql = "from Analysis a where a.sampleItem.sample.priority = :oderpriority and a.statusId in (" + + " :statusIds)"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("oderpriority", priority.name()); + query.setParameterList("statusIds", statusIds); + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysesBySampleIdAndStatusId"); + } + + return null; } - return null; - } + /** + * bugzilla 1993 (part of 1942) getAnalysesReadyToBeReported() - returns the + * tests that should be updated with a printed date of today's date (see + * ResultsReport) + */ + @Override + @Transactional(readOnly = true) + public List getAnalysesReadyToBeReported() throws LIMSRuntimeException { + try { + List analysisStatusesToInclude = new ArrayList<>(); + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusReleased()); + + List sampleStatusesToInclude = new ArrayList<>(); + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); + + String sql = "select distinct anal.id\n" + " from\n" + " sample samp,\n" + + " test_analyte ta,\n" + " analysis anal,\n" + + " sample_item sampitem,\n" + " test test,\n" + " result res\n" + + "\n" + " where\n" + " ta.test_id = test.id and\n" + + " ta.analyte_id=res.analyte_id and\n" + " anal.id = res.analysis_id and\n" + + " anal.test_id = test.id and\n" + " anal.sampitem_id = sampitem. id and\n" + + " sampitem.samp_id = samp.id\n" + " and res.is_reportable = 'Y'\n" + + " and anal.is_reportable = 'Y'\n" + " and anal.printed_date is null\n" + + " and anal.status in (:analysisStatusesToInclude)\n" + + " and samp.status in(:sampleStatusesToInclude)\n" + + " --bugzilla 2028 - there is corresponding sql in main_report.jrxml and" + + " test_results.jrxml to make sure we exclude the samples for which tests qa events" + + " are not completed\n" + " --isQaEventsCompleted is 'Y' or 'N'\n" + + " --------------if there are no qa events for this test then" + + " isQaEventsCompleted = 'Y'\n" + + " and 'Y' = case when (select count(*) from analysis_qaevent aq where" + + " aq.analysis_id = anal.id)= 0 then 'Y'\n" + + " --if there are no holdable qa events for this test then " + + " isQaEventsCompleted = 'Y'\n" + + " when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --if there the holdable qa events for this test are" + + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" + + " when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --else isQaEventsCompleted = 'N'\n" + + " else 'N'end"; + return entityManager.unwrap(Session.class).createQuery(sql, Analysis.class) + .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) + .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude).list(); + + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getAnalysesReadyToBeReported()", e); + } + } - @Override - @Transactional(readOnly = true) - public List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) - throws LIMSRuntimeException { + @Override + @Transactional(readOnly = true) + public List getAllChildAnalysesByResult(Result result) throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.parentResult = :param and a.status NOT IN (:param2)"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", result.getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param2", statusesToExclude); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getallChildAnalysesByResult()", e); + } + } - String sql = "from Analysis a where a.releasedDate = :releasedDate and a.statusId = :statusId "; + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException { + try { + String sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem.id = :param " + + "and a.status NOT IN (:param2) " + "order by a.test.id, a.revision desc"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", sampleItem.getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param2", statusesToExclude); + return query.list(); + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); + } + } - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("releasedDate", completedDate); - query.setParameter("statusId", Integer.parseInt(statusId)); + // bugzilla 2300 (separate method for sample tracking) - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) + throws LIMSRuntimeException { + try { + String sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem.id = :param " + + "order by a.test.id, a.revision desc"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", sampleItem.getId()); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); + } } - return null; - } + @Override + @Transactional(readOnly = true) + public List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException { + try { + String sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) NOT IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem.id = :param " + + "and a.status NOT IN (:param2) " + "order by a.test.id, a.revision desc"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", sampleItem.getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param2", statusesToExclude); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getRevisionHistoryOfAnalysesBySample()", e); + } + } - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOn(Date collectionDate) throws LIMSRuntimeException { + @Override + @Transactional(readOnly = true) + public List getRevisionHistoryOfAnalysesBySampleAndTest(SampleItem sampleItem, Test test, + boolean includeLatestRevision) throws LIMSRuntimeException { + try { + String sql = ""; + if (includeLatestRevision) { + sql = "from Analysis a " + "where a.sampleItem.id = :param " + "and a.status NOT IN (:param3) " + + "and a.test.id = :param2 " + "order by a.test.id, a.revision desc"; + } else { + sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) NOT IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem.id = :param " + + "and a.status NOT IN (:param3) " + "and a.test.id = :param2 " + + "order by a.test.id, a.revision desc"; + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", sampleItem.getId()); + query.setParameter("param2", test.getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param3", statusesToExclude); + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getRevisionHistoryOfAnalysesBySample()", e); + } + } - try { - String sql = "from Analysis a where DATE(a.startedDate) = DATE(:startedDate)"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("startedDate", collectionDate); + @Override + @Transactional(readOnly = true) + public List getAllMaxRevisionAnalysesPerTest(Test test) throws LIMSRuntimeException { + try { + String sql = "from Analysis a where (a.sampleItem.id, a.revision) IN " + + "(select b.sampleItem.id, max(b.revision) from Analysis b " + "group by b.sampleItem.id) " + + "and a.test = :param " + "and a.status NOT IN (:param2) " + + "order by a.sampleItem.sample.accessionNumber"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", test.getId()); + + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param2", statusesToExclude); + + return query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getAllMaxRevisionAnalysesPerTest()", e); + } + } - List list = query.list(); - return list; + // bugzilla 2227, 2258 + @Override + @Transactional + public List getMaxRevisionAnalysesReadyToBeReported() throws LIMSRuntimeException { + try { + List analysisStatusesToInclude = new ArrayList<>(); + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusReleased()); + + List sampleStatusesToInclude = new ArrayList<>(); + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); + + String sql = "select distinct anal.id\n" + " from\n" + " sample samp,\n" + + " test_analyte ta,\n" + " analysis anal,\n" + + " sample_item sampitem,\n" + " test test,\n" + " result res\n" + + "\n" + " where\n" + " (\n" + " (\n" + + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" + " )IN(\n" + + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" + + " from\n" + " analysis anal2\n" + " group by\n" + + " anal2.SAMPITEM_ID ,\n" + " anal2.TEST_ID\n" + + " )\n" + " ) and\n" + " ta.test_id = test.id and\n" + + " ta.analyte_id=res.analyte_id and\n" + " anal.id = res.analysis_id and\n" + + " anal.test_id = test.id and\n" + " anal.sampitem_id = sampitem. id and\n" + + " sampitem.samp_id = samp.id\n" + " and res.is_reportable = 'Y'\n" + + " and anal.is_reportable = 'Y'\n" + " and anal.printed_date is null\n" + + " and anal.status in (:analysisStatusesToInclude)\n" + + " and samp.status in(:sampleStatusesToInclude)\n" + + " --bugzilla 2028 make sure we exclude the samples for which tests qa" + + " events are not completed\n" + " --isQaEventsCompleted is 'Y' or 'N'\n" + + " --------------if there are no qa events for this test then" + + " isQaEventsCompleted = 'Y'\n" + + " and 'Y' = case when (select count(*) from analysis_qaevent aq where" + + " aq.analysis_id = anal.id)= 0 then 'Y'\n" + + " --if there are no holdable qa events for this test then " + + " isQaEventsCompleted = 'Y'\n" + + " when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --if there the holdable qa events for this test are" + + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" + + " when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --else isQaEventsCompleted = 'N'\n" + + " else 'N'\n" + " end"; + return entityManager.unwrap(Session.class).createNativeQuery(sql, Analysis.class) + .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) + .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude).list(); + + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesReadyToBeReported()", e); + } + } - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOn"); + // bugzilla 1900 + @Override + @Transactional + public List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers) + throws LIMSRuntimeException { + List list = new Vector<>(); + try { + List analysisStatusesToInclude = new ArrayList<>(); + // see question in 1900 should this be released or results completed + // status? + // answer: results completed + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); + + List sampleStatusesToInclude = new ArrayList<>(); + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusEntry2Complete()); + // see question in 1900 - should this be included? Yes + sampleStatusesToInclude.add(SystemConfiguration.getInstance().getSampleStatusReleased()); + + if (accessionNumbers != null && accessionNumbers.size() > 0) { + String sql = "select distinct anal.id\n" + " from\n" + " sample samp,\n" + + " test_analyte ta,\n" + " analysis anal,\n" + + " sample_item sampitem,\n" + " test test,\n" + + " result res\n" + "\n" + " where\n" + " (\n" + " (\n" + + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" + " )IN(\n" + + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" + + " from\n" + " analysis anal2\n" + " group by\n" + + " anal2.SAMPITEM_ID ,\n" + " anal2.TEST_ID\n" + + " )\n" + " ) and\n" + " ta.test_id = test.id and\n" + + " ta.analyte_id=res.analyte_id and\n" + + " anal.id = res.analysis_id and\n" + " anal.test_id = test.id and\n" + + " anal.sampitem_id = sampitem. id and\n" + + " sampitem.samp_id = samp.id\n" + " and res.is_reportable = 'Y'\n" + + " and anal.is_reportable = 'Y'\n" + " and anal.printed_date is null\n" + + " and anal.status in (:analysisStatusesToInclude)\n" + + " and samp.status in(:sampleStatusesToInclude)\n" + + " and samp.accession_number in(:samplesToInclude)\n" + + " --bugzilla 2509 removed exclusion of holdable not completed qa" + " events\n" + + " --bugzilla 2028 make sure we exclude the samples for which tests qa" + + " events are not completed\n" + " --isQaEventsCompleted is 'Y' or 'N'\n" + + " --------------if there are no qa events for this test then" + + " isQaEventsCompleted = 'Y'\n" + + " --and 'Y' = case when (select count(*) from analysis_qaevent aq" + + " where aq.analysis_id = anal.id)= 0 then 'Y'\n" + + " --if there are no holdable qa events for this test then " + + " isQaEventsCompleted = 'Y'\n" + + " --when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --if there the holdable qa events for this test are" + + " completed (completed date is not null) then isQaEventsCompleted = 'Y'\n" + + " --when (select count(*) from analysis_qaevent aq," + + " qa_event q where aq.analysis_id = anal.id and q.id = aq.qa_event_id and" + + " aq.completed_date is null and q.is_holdable = 'Y') = 0 then 'Y'\n" + + " --else isQaEventsCompleted = 'N'\n" + + " --else 'N'\n" + " --end"; + list = entityManager.unwrap(Session.class).createNativeQuery(sql) + .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude) + .setParameterList("sampleStatusesToInclude", sampleStatusesToInclude) + .setParameterList("samplesToInclude", accessionNumbers).list(); + } + + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getMaxRevisionAnalysesReadyForReportPreviewBySample()", e); + } + return list; } - return null; - } + // bugzilla 1856 + @Override + @Transactional + public List getAnalysesAlreadyReportedBySample(Sample sample) throws LIMSRuntimeException { + try { + String sql = "select distinct anal.id\n" + " from\n" + " sample samp,\n" + + " test_analyte ta,\n" + " analysis anal,\n" + + " sample_item sampitem,\n" + " test test,\n" + " result res\n" + + "\n" + " where\n" + " (\n" + " (\n" + + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" + " )IN(\n" + + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" + + " from\n" + " analysis anal2\n" + " group by\n" + + " anal2.SAMPITEM_ID ,\n" + " anal2.TEST_ID\n" + + " )\n" + " ) and\n" + " samp.id = :sampleId and\n" + + " ta.test_id = test.id and\n" + " ta.analyte_id=res.analyte_id and\n" + + " anal.id = res.analysis_id and\n" + " anal.test_id = test.id and\n" + + " anal.sampitem_id = sampitem. id and\n" + " sampitem.samp_id = samp.id\n" + + " and anal.printed_date is not null"; + return entityManager.unwrap(Session.class).createNativeQuery(sql).setParameter("sampleId", sample.getId()) + .list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getAnalysesAlreadyReportedBySample()", e); + } + } - @Override - @Transactional(readOnly = true) - public List getAnalysisCollectedOnExcludedByStatusId( - Date collectionDate, Set statusIds) throws LIMSRuntimeException { - if (statusIds == null || statusIds.isEmpty()) { - return getAnalysisStartedOn(collectionDate); + // bugzilla 2264 + @Override + @Transactional + public List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) + throws LIMSRuntimeException { + try { + List analysisStatusesToInclude = new ArrayList<>(); + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); + // bugzilla 2264 per Nancy add results completed status to pending + // tests + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); + + String sql = "select\n" + " distinct anal.id\n" + " from\n" + " sample_item sampitem,\n" + + " sample samp,\n" + " analysis anal,\n" + " test test\n" + "\n" + " where\n" + + " (\n" + " (\n" + " anal.SAMPITEM_ID , anal.TEST_ID , anal.REVISION\n" + + " )IN(\n" + " select anal2.SAMPITEM_ID, anal2.TEST_ID, max(anal2.REVISION)\n" + + " from\n" + " analysis anal2\n" + " group by\n" + + " anal2.SAMPITEM_ID ,\n" + " anal2.TEST_ID\n" + " )\n" + " ) and\n" + + " samp.id = :sampleId\n" + " and sampitem.samp_id = samp.id\n" + + " and anal.sampitem_id = sampitem. id\n" + " and anal.test_id = test.id\n" + " and\n" + + "\n" + " (select count(*)\n" + " from test_analyte t_a\n" + + " where t_a.test_id = test.id and\n" + " (t_a.id) in (\n" + + " select ta.id\n" + " from test_analyte ta,\n" + + " analysis anal2,\n" + + " sample_item sampitem,\n" + + " sample samp,\n" + " test test\n" + + " where\n" + " samp.id = :sampleId and\n" + + " sampitem.samp_id = samp.id and\n" + + " anal2.sampitem_id = sampitem. id and\n" + + " anal2.test_id = test.id and\n" + + " ta.test_id = test.id and\n" + + " ta.is_reportable = 'Y' and\n" + + " anal2.is_reportable = 'Y' and\n" + + " anal2.printed_date is null and\n" + + " anal.id = anal2.id and\n" + + " anal2.status in (:analysisStatusesToInclude)\n" + + " )\n" + " ) > 0"; + return entityManager.unwrap(Session.class).createNativeQuery(sql).setParameter("sampleId", sample.getId()) + .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude).list(); + + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionPendingAnalysesReadyToBeReportedBySample()", + e); + } } - String sql = - "from Analysis a where DATE(a.sampleItem.collectionDate) = DATE(:startedDate) and" - + " a.statusId not in ( :statusList )"; + // bugzilla 1900 + @SuppressWarnings("unchecked") + @Override + @Transactional(readOnly = true) + public List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) + throws LIMSRuntimeException { + List list = new Vector<>(); + + try { + + List analysisStatusesToInclude = new ArrayList<>(); + analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); + // see question in 1900 do we need to include this? + // Answer NO + // analysisStatusesToInclude.add(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); + + list = entityManager.unwrap(Session.class) + .getNamedQuery("analysis.getMaxRevisionPendingAnalysesReadyToBeReportedBySample") + .setParameter("sampleId", sample.getId()) + .setParameterList("analysisStatusesToInclude", analysisStatusesToInclude).list(); - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("startedDate", collectionDate); - query.setParameterList("statusList", statusIds); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getMaxRevisionPendingAnalysesReadyForReportPreviewBySample()", e); + } - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + return list; } - return null; - } + @Override + @Transactional(readOnly = true) + public Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) throws LIMSRuntimeException { + Analysis previousAnalysis = null; + try { + // Use an expression to read in the Analysis whose + // revision is 1 less than the analysis passed in + + String sql = "from Analysis a where a.revision = :param and a.sampleItem = :param2 and a.test =" + + " :param3 and a.status NOT IN (:param4)"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + + String revisionString = analysis.getRevision(); + int revision = 0; + if (!StringUtil.isNullorNill(revisionString)) { + try { + revision = Integer.parseInt(revisionString); + } catch (NumberFormatException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getPreviousAnalysisForAmendedAnalysis()", e); + } + } + + query.setParameter("param", String.valueOf((revision - 1))); + query.setParameter("param2", analysis.getSampleItem()); + query.setParameter("param3", analysis.getTest()); + + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param4", statusesToExclude); + List list = query.list(); + if ((list != null) && !list.isEmpty()) { + previousAnalysis = list.get(0); + } + + } catch (RuntimeException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Exception occurred in getPreviousAnalysisForAmendedAnalysis", e); + } + return previousAnalysis; + } - @Override - @Transactional(readOnly = true) - public List getAnalysisCollectedOn(Date collectionDate) throws LIMSRuntimeException { + @Override + @Transactional(readOnly = true) + public void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) throws LIMSRuntimeException { - try { - String sql = "from Analysis a where a.sampleItem.collectionDate = :startedDate"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("startedDate", collectionDate); + try { + Analysis anal = null; + String sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem = :param " + + "and a.status NOT IN (:param3) " + "and a.test = :param2"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", analysis.getSampleItem().getId()); + query.setParameter("param2", analysis.getTest().getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param3", statusesToExclude); + anal = query.uniqueResult(); + + if (anal != null) { + PropertyUtils.copyProperties(analysis, anal); + } else { + analysis.setId(null); + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysisBySampleAndTest()", e); + } + } - List list = query.list(); - return list; + @Override + @Transactional(readOnly = true) + public List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) throws LIMSRuntimeException { + + List list = new Vector<>(); + try { - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOn"); + String sql = "from Analysis a where (a.sampleItem.id, a.test.id, a.revision) IN " + + "(select b.sampleItem.id, b.test.id, max(b.revision) from Analysis b " + + "group by b.sampleItem.id, b.test.id) " + "and a.sampleItem.id = :param " + + "and a.status NOT IN (:param2) " + "and a.parentAnalysis is null " + + "order by a.test.id, a.revision desc"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("param", sampleItem.getId()); + List statusesToExclude = new ArrayList<>(); + statusesToExclude.add(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); + query.setParameterList("param2", statusesToExclude); + list = query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analysis getMaxRevisionAnalysesBySample()", e); + } + + return list; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysesForStatusId(String statusId) throws LIMSRuntimeException { - /** - * @see - * org.openelisglobal.analysis.dao.AnalysisDAO#getAnalysisBySampleAndTestIds(java.lang.String, - * java.util.List) - */ - @Override - @Transactional(readOnly = true) - public List getAnalysisBySampleAndTestIds(String sampleId, List testIds) { - List list = null; - try { - if (testIds == null || testIds.size() == 0) { - return new ArrayList<>(); - } - String sql = - "from Analysis a WHERE a.sampleItem.sample.id = :sampleId AND a.test.id IN ( :testIds )"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleId", Integer.valueOf(sampleId)); - query.setParameterList("testIds", testIds); - - list = query.list(); - } catch (HibernateException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in getAnalysisStartedOn()", e); - } - - return list; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestSectionAndCompletedDateRange( - String sectionID, Date lowDate, Date highDate) throws LIMSRuntimeException { - - String sql = - "From Analysis a where a.testSection.id = :testSectionId and a.completedDate BETWEEN" - + " :lowDate AND :highDate"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testSectionId", Integer.parseInt(sectionID)); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - - List list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisByTestSectionAndCompletedDateRange"); - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) - throws LIMSRuntimeException { - String sql = - "From Analysis a where a.startedDate BETWEEN :lowDate AND :highDate or a.completedDate" - + " BETWEEN :lowDate AND :highDate"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - - List list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOrCompletedInDateRange"); - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange( - Date lowDate, Date highDate, String testId, List testSectionIds) - throws LIMSRuntimeException { - String sql = - "FROM Analysis a WHERE a.startedDate BETWEEN :lowDate AND :highDate AND a.test.id = :testId" - + " AND a.testSection.id IN ( :testSectionIds )"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - query.setParameter("testId", Integer.parseInt(testId)); - query.setParameterList("testSectionIds", testSectionIds); - List list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedInDateRange"); - } - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleId(String id) throws LIMSRuntimeException { - List list = null; - if (!GenericValidator.isBlankOrNull(id)) { - try { - String sql = "from Analysis a where a.sampleItem.sample.id = :sampleId"; - - Query query = - entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleId", Integer.parseInt(id)); - - list = query.list(); - } catch (RuntimeException e) { - handleException(e, "getAnalysesBySampleId"); - } - } - return list; - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatus( - List testIds, List analysisStatusList, List sampleStatusList) { - String sql = - "From Analysis a WHERE a.test.id IN (:testIds) AND a.statusId IN (:analysisStatusList) AND" - + " a.sampleItem.sample.statusId IN (:sampleStatusList)"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("testIds", testIds); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - - List analysisList = query.list(); - - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getAllAnalysisByTestSectionAndStatus"); - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List testIdList, - List analysisStatusList, - List sampleStatusList, - Date lowDate, - Date highDate) { - List testList = new ArrayList<>(); - try { - String sql = - "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:analysisStatusList)" - + " and a.sampleItem.sample.statusId IN (:sampleStatusList) and a.completedDate" - + " BETWEEN :lowDate AND :highDate order by a.sampleItem.sample.accessionNumber"; - - for (Integer testId : testIdList) { - testList.add(testId); - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("testList", testList); - query.setParameterList("sampleStatusList", sampleStatusList); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - - List analysisList = query.list(); - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getAllAnalysisByTestsAndStatusAndCompletedDateRange"); - } - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) - throws LIMSRuntimeException { - - String sql = - "From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" - + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList) ORDER" - + " BY a.sampleItem.sample.accessionNumber"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - List analysisList = query.list(); - - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getAllAnalysisByTestSectionAndStatus"); - } - - return null; - } - - @Override - public List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) { - - String sql = - "From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" - + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList) ORDER" - + " BY a.sampleItem.sample.accessionNumber"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); - - List analysisList = query.list(); - - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getPageAnalysisByTestSectionAndStatus"); - } + List list = null; - return null; - } + try { + String sql = "from Analysis a where a.statusId = :statusId"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("statusId", Integer.parseInt(statusId)); + + list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisForStatusId"); + } - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOnRangeByStatusId( - Date lowDate, Date highDate, String statusID) throws LIMSRuntimeException { - String sql = - "From Analysis a where a.statusId = :statusID and a.startedDate BETWEEN :lowDate AND" - + " :highDate"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("statusID", Integer.parseInt(statusID)); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); - - List analysisList = query.list(); - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getAnalysisStartedOnRangeByStatusId"); + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysisStartedOn(collectionDate); + } - @Override - @Transactional(readOnly = true) - public List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) - throws LIMSRuntimeException { - String sql = - "From Analysis a where a.completedDate >= :lowDate AND a.completedDate < :highDate"; + String sql = "from Analysis a where a.startedDate = :startedDate and a.statusId not in ( :statusList )"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("startedDate", collectionDate); + query.setParameterList("statusList", statusIds); + + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + } + + return null; + } - List analysisList = query.list(); - return analysisList; + @Override + @Transactional(readOnly = true) + public List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) + throws LIMSRuntimeException { - } catch (HibernateException e) { - handleException(e, "getAnalysisCompletedInRange"); + String sql = "from Analysis a where a.releasedDate = :releasedDate and a.statusId = :statusId "; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("releasedDate", completedDate); + query.setParameter("statusId", Integer.parseInt(statusId)); + + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + } + + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOn(Date collectionDate) throws LIMSRuntimeException { - @Override - @Transactional(readOnly = true) - public List getAnalysisEnteredAfterDate(Timestamp date) throws LIMSRuntimeException { - String sql = "From Analysis a where a.enteredDate > :date"; + try { + String sql = "from Analysis a where DATE(a.startedDate) = DATE(:startedDate)"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("startedDate", collectionDate); - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("date", date); + List list = query.list(); + return list; - List analysisList = query.list(); - return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOn"); + } - } catch (HibernateException e) { - handleException(e, "getAnalysisEnteredAfterDate"); + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisCollectedOnExcludedByStatusId(Date collectionDate, Set statusIds) + throws LIMSRuntimeException { + if (statusIds == null || statusIds.isEmpty()) { + return getAnalysisStartedOn(collectionDate); + } + + String sql = "from Analysis a where DATE(a.sampleItem.collectionDate) = DATE(:startedDate) and" + + " a.statusId not in ( :statusList )"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("startedDate", collectionDate); + query.setParameterList("statusList", statusIds); + + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOnExcludedByStatusId"); + } - @Override - @Transactional(readOnly = true) - public List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) - throws LIMSRuntimeException { - if (GenericValidator.isBlankOrNull(accessionNumber) || GenericValidator.isBlankOrNull(testId)) { - return new ArrayList<>(); + return null; } - String sql = - "From Analysis a where a.sampleItem.sample.accessionNumber = :accessionNumber and a.test.id" - + " = :testId"; + @Override + @Transactional(readOnly = true) + public List getAnalysisCollectedOn(Date collectionDate) throws LIMSRuntimeException { - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("accessionNumber", accessionNumber); - query.setParameter("testId", Integer.parseInt(testId)); - List analysises = query.list(); - return analysises; - } catch (HibernateException e) { - handleException(e, "getAnalysisByAccessionAndTestId"); + try { + String sql = "from Analysis a where a.sampleItem.collectionDate = :startedDate"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("startedDate", collectionDate); + + List list = query.list(); + return list; + + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOn"); + } + + return null; } - return null; - } + /** + * @see org.openelisglobal.analysis.dao.AnalysisDAO#getAnalysisBySampleAndTestIds(java.lang.String, + * java.util.List) + */ + @Override + @Transactional(readOnly = true) + public List getAnalysisBySampleAndTestIds(String sampleId, List testIds) { + List list = null; + try { + if (testIds == null || testIds.size() == 0) { + return new ArrayList<>(); + } + String sql = "from Analysis a WHERE a.sampleItem.sample.id = :sampleId AND a.test.id IN ( :testIds )"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleId", Integer.valueOf(sampleId)); + query.setParameterList("testIds", testIds); + + list = query.list(); + } catch (HibernateException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in getAnalysisStartedOn()", e); + } - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestNamesAndCompletedDateRange( - List testNames, Date lowDate, Date highDate) throws LIMSRuntimeException { - if (testNames.isEmpty()) { - return new ArrayList<>(); + return list; } - String sql = - "From Analysis a where (a.test.localizedTestName.english in (:testNames) or" - + " a.test.localizedTestName.french in (:testNames)) and a.completedDate BETWEEN" - + " :lowDate AND :highDate"; + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestSectionAndCompletedDateRange(String sectionID, Date lowDate, Date highDate) + throws LIMSRuntimeException { + + String sql = "From Analysis a where a.testSection.id = :testSectionId and a.completedDate BETWEEN" + + " :lowDate AND :highDate"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("testNames", testNames); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testSectionId", Integer.parseInt(sectionID)); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisByTestSectionAndCompletedDateRange"); + } - List list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisByTestNamesAndCompletedDateRange"); + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) + throws LIMSRuntimeException { + String sql = "From Analysis a where a.startedDate BETWEEN :lowDate AND :highDate or a.completedDate" + + " BETWEEN :lowDate AND :highDate"; - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestDescriptionAndCompletedDateRange( - List descriptions, Date lowDate, Date highDate) throws LIMSRuntimeException { - if (descriptions.isEmpty()) { - return new ArrayList<>(); - } + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOrCompletedInDateRange"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange(Date lowDate, Date highDate, + String testId, List testSectionIds) throws LIMSRuntimeException { + String sql = "FROM Analysis a WHERE a.startedDate BETWEEN :lowDate AND :highDate AND a.test.id = :testId" + + " AND a.testSection.id IN ( :testSectionIds )"; - String sql = - "From Analysis a where a.test.description in (:descriptions) and a.completedDate BETWEEN" - + " :lowDate AND :highDate"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + query.setParameter("testId", Integer.parseInt(testId)); + query.setParameterList("testSectionIds", testSectionIds); + List list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedInDateRange"); + } + return null; + } - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("descriptions", descriptions); - query.setParameter("lowDate", lowDate); - query.setParameter("highDate", highDate); + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleId(String id) throws LIMSRuntimeException { + List list = null; + if (!GenericValidator.isBlankOrNull(id)) { + try { + String sql = "from Analysis a where a.sampleItem.sample.id = :sampleId"; - List list = query.list(); - return list; - } catch (HibernateException e) { - handleException(e, "getAnalysisByTestDescriptionsAndCompletedDateRange"); + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleId", Integer.parseInt(id)); + + list = query.list(); + } catch (RuntimeException e) { + handleException(e, "getAnalysesBySampleId"); + } + } + return list; } - return null; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId) - throws LIMSRuntimeException { - try { - String sql = - "from Analysis a where a.sampleItem.id = :sampleItemId and a.statusId = :statusId"; + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatus(List testIds, List analysisStatusList, + List sampleStatusList) { + String sql = "From Analysis a WHERE a.test.id IN (:testIds) AND a.statusId IN (:analysisStatusList) AND" + + " a.sampleItem.sample.statusId IN (:sampleStatusList)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("testIds", testIds); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + + List analysisList = query.list(); - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("sampleItemId", Integer.parseInt(sampleItemId)); - query.setParameter("statusId", Integer.parseInt(statusId)); + return analysisList; - List analysisList = query.list(); - return analysisList; - } catch (RuntimeException e) { - handleException(e, "getAnalysesBySampleItemIdAndStatusId"); - } - - return null; // will never get here - } - - @Override - @Transactional(readOnly = true) - public Analysis getAnalysisById(String analysisId) throws LIMSRuntimeException { - if (analysisId == null) { - return null; + } catch (HibernateException e) { + handleException(e, "getAllAnalysisByTestSectionAndStatus"); + } + + return null; } - try { - Analysis analysis = entityManager.unwrap(Session.class).get(Analysis.class, analysisId); - return analysis; - } catch (RuntimeException e) { - handleException(e, "getAnalysisById"); + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List testIdList, + List analysisStatusList, List sampleStatusList, Date lowDate, Date highDate) { + List testList = new ArrayList<>(); + try { + String sql = "from Analysis a where a.test.id IN (:testList) and a.statusId IN (:analysisStatusList)" + + " and a.sampleItem.sample.statusId IN (:sampleStatusList) and a.completedDate" + + " BETWEEN :lowDate AND :highDate order by a.sampleItem.sample.accessionNumber"; + + for (Integer testId : testIdList) { + testList.add(testId); + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("testList", testList); + query.setParameterList("sampleStatusList", sampleStatusList); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List analysisList = query.list(); + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getAllAnalysisByTestsAndStatusAndCompletedDateRange"); + } + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) throws LIMSRuntimeException { - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdTestIdAndStatusId( - List sampleIdList, List testIdList, List statusIdList) - throws LIMSRuntimeException { - - if (sampleIdList.isEmpty() || testIdList.isEmpty() || statusIdList.isEmpty()) { - return new ArrayList<>(); - } - String sql = - "from Analysis a where a.sampleItem.sample.id in (:sampleIdList) and a.test.id in" - + " (:testIdList) and a.statusId in (:statusIdList) order by a.releasedDate desc"; + String sql = "From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" + + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList) ORDER" + + " BY a.sampleItem.sample.accessionNumber"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + List analysisList = query.list(); - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList("sampleIdList", sampleIdList); - query.setParameterList("testIdList", testIdList); - query.setParameterList("statusIdList", statusIdList); - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysesBySampleIdTestIdAndStatusId"); + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getAllAnalysisByTestSectionAndStatus"); + } + + return null; + } + + @Override + public List getPageAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) { + + String sql = "From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" + + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList) ORDER" + + " BY a.sampleItem.sample.accessionNumber"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); + + List analysisList = query.list(); + + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getPageAnalysisByTestSectionAndStatus"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID) + throws LIMSRuntimeException { + String sql = "From Analysis a where a.statusId = :statusID and a.startedDate BETWEEN :lowDate AND" + + " :highDate"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("statusID", Integer.parseInt(statusID)); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List analysisList = query.list(); + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getAnalysisStartedOnRangeByStatusId"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) + throws LIMSRuntimeException { + String sql = "From Analysis a where a.completedDate >= :lowDate AND a.completedDate < :highDate"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List analysisList = query.list(); + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getAnalysisCompletedInRange"); + } + + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisEnteredAfterDate(Timestamp date) throws LIMSRuntimeException { + String sql = "From Analysis a where a.enteredDate > :date"; - @Override - public List get(List ids) { - String sql = "from Analysis a where a.id in (:ids)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("date", date); - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameterList( - "ids", ids.stream().map(e -> Integer.parseInt(e)).collect(Collectors.toList())); - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "get"); - } - // TODO Auto-generated method stub - return null; - } - - @Override - public int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) { - - String hql = - "SELECT COUNT(*) From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" - + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList)"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - - Long analysisList = query.uniqueResult(); - - return analysisList.intValue(); - - } catch (HibernateException e) { - handleException(e, "getAllAnalysisByTestSectionAndStatus"); - } - - return 0; - } - - @Override - public int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList) { - - String hql = - "SELECT COUNT(*) From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" - + " (:analysisStatusList)"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); - query.setParameter("testSectionId", Integer.parseInt(testSectionId)); - query.setParameterList("analysisStatusList", analysisStatusList); - - Long analysisList = query.uniqueResult(); - - return analysisList.intValue(); - - } catch (HibernateException e) { - handleException(e, "getAllAnalysisByTestSectionAndStatus"); - } - - return 0; - } - - @Override - public List getPageAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber) { - - String sql = - "From Analysis a WHERE a.sampleItem.sample.accessionNumber >= :accessionNumber" // - + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // - + " AND a.statusId IN (:analysisStatusList)" // - + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // - + " ORDER BY a.sampleItem.sample.accessionNumber"; // - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("accessionNumber", accessionNumber); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); - - List analysisList = query.list(); - - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getPageAnalysisByStatusFromAccession"); - } - - return null; - } - - @Override - public List getPageAnalysisByStatusFromAccession( - List analysisStatusList, - List sampleStatusList, - String accessionNumber, - String upperRangeAccessionNumber, - boolean doRange, - boolean finished) { - - if (finished) { - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.Finalized))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.BiologistRejected))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.Canceled))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.NotStarted))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.NonConforming_depricated))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.SampleRejected))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.TechnicalAcceptance))); - analysisStatusList.add( - Integer.parseInt( - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.TechnicalRejected))); - } - - String sql = ""; - if (doRange && StringUtils.isNotBlank(upperRangeAccessionNumber)) - sql = - "From Analysis a WHERE a.sampleItem.sample.accessionNumber between :accessionNumber and" - + " :upperRangeAccessionNumber" // - + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // - + " AND a.statusId IN (:analysisStatusList)" // - + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // - + " ORDER BY a.sampleItem.sample.accessionNumber"; // - else - sql = - "From Analysis a WHERE a.sampleItem.sample.accessionNumber = :accessionNumber" // - + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // - + " AND a.statusId IN (:analysisStatusList)" // - + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // - + " ORDER BY a.sampleItem.sample.accessionNumber"; // - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("accessionNumber", accessionNumber); - if (StringUtils.isNotBlank(upperRangeAccessionNumber)) { - query.setParameter("upperRangeAccessionNumber", upperRangeAccessionNumber); - } - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); - - List analysisList = query.list(); - - return analysisList; - - } catch (HibernateException e) { - handleException(e, "getPageAnalysisByStatusFromAccession"); - } - - return null; - } - - @Override - public int getCountAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber) { - - String hql = - "SELECT COUNT(*) From Analysis a WHERE " - + " a.statusId IN (:analysisStatusList)" - + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); - query.setParameterList("analysisStatusList", analysisStatusList); - query.setParameterList("sampleStatusList", sampleStatusList); - - Long analysisList = query.uniqueResult(); - - return analysisList.intValue(); - - } catch (HibernateException e) { - handleException(e, "getCountAnalysisByStatusFromAccession"); - } - - return 0; - } - - @Override - public List getAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate) { - String hql = - "FROM Analysis a WHERE a.enteredDate BETWEEN :lowerDate AND :upperDate AND" - + " a.sampleItem.sample.id IN (SELECT sr.sampleId FROM SampleRequester sr WHERE" - + " sr.requesterId = :requesterId AND sr.requesterTypeId = (SELECT rt.id FROM" - + " RequesterType rt WHERE rt.requesterType = 'organization' ))"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); - query.setParameter("requesterId", Integer.parseInt(referringSiteId)); - query.setParameter("lowerDate", lowerDate.atStartOfDay()); - query.setParameter("upperDate", upperDate.atTime(LocalTime.MAX)); - return query.list(); - } catch (HibernateException e) { - handleException(e, "getAnalysisForSiteBetweenResultDates"); - } - return new ArrayList<>(); - } - - @Override - public List getStudyAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate) { - String hql = - "FROM Analysis a WHERE a.releasedDate BETWEEN :lowerDate AND :upperDate AND" - + " a.sampleItem.sample.id IN (SELECT so.sample.id FROM SampleOrganization so WHERE" - + " so.organization.id = :requesterId )"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); - query.setParameter("requesterId", Integer.parseInt(referringSiteId)); - query.setParameter("lowerDate", lowerDate.atStartOfDay()); - query.setParameter("upperDate", upperDate.atTime(LocalTime.MAX)); - return query.list(); - } catch (HibernateException e) { - handleException(e, "getAnalysisForSiteBetweenResultDates"); - } - return new ArrayList<>(); - } - - @Override - public int getCountOfAnalysesForStatusIds(List statusIdList) { - String hql = "SELECT COUNT(*) From Analysis a WHERE a.statusId IN (:analysisStatusList)"; - try { - Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); - query.setParameterList("analysisStatusList", statusIdList); - - Long count = query.uniqueResult(); - return count.intValue(); - - } catch (HibernateException e) { - handleException(e, "getCountOfAnalysesForStatusIds"); - } - - return 0; - } - - @Override - public int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds) { - String sql = - "SELECT COUNT(*) From Analysis a where a.releasedDate = :releasedDate and a.statusId in (" - + " :statusList )"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); - query.setParameter("releasedDate", completedDate); - query.setParameterList("statusList", statusIds); - - Long count = query.uniqueResult(); - return count.intValue(); - } catch (HibernateException e) { - handleException(e, "getCountOfAnalysisCompletedOnByStatusId"); - } - - return 0; - } - - @Override - public int getCountOfAnalysisStartedOnExcludedByStatusId( - Date collectionDate, Set statusIds) { - - String sql = - "SELECT COUNT(*) from Analysis a where a.startedDate = :startedDate and a.statusId not in (" - + " :statusList )"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); - query.setParameter("startedDate", collectionDate); - query.setParameterList("statusList", statusIds); - - Long count = query.uniqueResult(); - return count.intValue(); - } catch (HibernateException e) { - handleException(e, "getCountOfAnalysisStartedOnExcludedByStatusId"); - } - - return 0; - } - - @Override - public int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds) { - String sql = - "SELECT COUNT(*) from Analysis a where a.startedDate = :startedDate and a.statusId in (" - + " :statusList )"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); - query.setParameter("startedDate", startedDate); - query.setParameterList("statusList", statusIds); - - Long count = query.uniqueResult(); - return count.intValue(); - } catch (HibernateException e) { - handleException(e, "getCountOfAnalysisStartedOnByStatusId"); - } - - return 0; - } - - @Override - public List getAnalysesResultEnteredOnExcludedByStatusId( - Date completedDate, Set statusIds) throws LIMSRuntimeException { - String sql = - "from Analysis a where a.completedDate = :completedDate and a.statusId not in ( :statusList" - + " )"; - - try { - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); - query.setParameter("completedDate", completedDate); - query.setParameterList("statusList", statusIds); + List analysisList = query.list(); + return analysisList; - List analysisList = query.list(); - return analysisList; - } catch (HibernateException e) { - handleException(e, "getAnalysisResultEnteredOnOnByStatusId"); + } catch (HibernateException e) { + handleException(e, "getAnalysisEnteredAfterDate"); + } + + return null; } - return null; - } + @Override + @Transactional(readOnly = true) + public List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) + throws LIMSRuntimeException { + if (GenericValidator.isBlankOrNull(accessionNumber) || GenericValidator.isBlankOrNull(testId)) { + return new ArrayList<>(); + } + + String sql = "From Analysis a where a.sampleItem.sample.accessionNumber = :accessionNumber and a.test.id" + + " = :testId"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("accessionNumber", accessionNumber); + query.setParameter("testId", Integer.parseInt(testId)); + List analysises = query.list(); + return analysises; + } catch (HibernateException e) { + handleException(e, "getAnalysisByAccessionAndTestId"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestNamesAndCompletedDateRange(List testNames, Date lowDate, + Date highDate) throws LIMSRuntimeException { + if (testNames.isEmpty()) { + return new ArrayList<>(); + } + + String sql = "From Analysis a where (a.test.localizedTestName.english in (:testNames) or" + + " a.test.localizedTestName.french in (:testNames)) and a.completedDate BETWEEN" + + " :lowDate AND :highDate"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("testNames", testNames); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisByTestNamesAndCompletedDateRange"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestDescriptionAndCompletedDateRange(List descriptions, Date lowDate, + Date highDate) throws LIMSRuntimeException { + if (descriptions.isEmpty()) { + return new ArrayList<>(); + } + + String sql = "From Analysis a where a.test.description in (:descriptions) and a.completedDate BETWEEN" + + " :lowDate AND :highDate"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("descriptions", descriptions); + query.setParameter("lowDate", lowDate); + query.setParameter("highDate", highDate); + + List list = query.list(); + return list; + } catch (HibernateException e) { + handleException(e, "getAnalysisByTestDescriptionsAndCompletedDateRange"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId) + throws LIMSRuntimeException { + try { + String sql = "from Analysis a where a.sampleItem.id = :sampleItemId and a.statusId = :statusId"; + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("sampleItemId", Integer.parseInt(sampleItemId)); + query.setParameter("statusId", Integer.parseInt(statusId)); + + List analysisList = query.list(); + return analysisList; + } catch (RuntimeException e) { + handleException(e, "getAnalysesBySampleItemIdAndStatusId"); + } + + return null; // will never get here + } + + @Override + @Transactional(readOnly = true) + public Analysis getAnalysisById(String analysisId) throws LIMSRuntimeException { + if (analysisId == null) { + return null; + } + try { + Analysis analysis = entityManager.unwrap(Session.class).get(Analysis.class, analysisId); + return analysis; + } catch (RuntimeException e) { + handleException(e, "getAnalysisById"); + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdTestIdAndStatusId(List sampleIdList, List testIdList, + List statusIdList) throws LIMSRuntimeException { + + if (sampleIdList.isEmpty() || testIdList.isEmpty() || statusIdList.isEmpty()) { + return new ArrayList<>(); + } + String sql = "from Analysis a where a.sampleItem.sample.id in (:sampleIdList) and a.test.id in" + + " (:testIdList) and a.statusId in (:statusIdList) order by a.releasedDate desc"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("sampleIdList", sampleIdList); + query.setParameterList("testIdList", testIdList); + query.setParameterList("statusIdList", statusIdList); + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysesBySampleIdTestIdAndStatusId"); + } + + return null; + } + + @Override + public List get(List ids) { + String sql = "from Analysis a where a.id in (:ids)"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameterList("ids", ids.stream().map(e -> Integer.parseInt(e)).collect(Collectors.toList())); + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "get"); + } + // TODO Auto-generated method stub + return null; + } + + @Override + public int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) { + + String hql = "SELECT COUNT(*) From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" + + " (:analysisStatusList) AND a.sampleItem.sample.statusId IN (:sampleStatusList)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + + Long analysisList = query.uniqueResult(); + + return analysisList.intValue(); + + } catch (HibernateException e) { + handleException(e, "getAllAnalysisByTestSectionAndStatus"); + } + + return 0; + } + + @Override + public int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList) { + + String hql = "SELECT COUNT(*) From Analysis a WHERE a.testSection.id = :testSectionId AND a.statusId IN" + + " (:analysisStatusList)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); + query.setParameter("testSectionId", Integer.parseInt(testSectionId)); + query.setParameterList("analysisStatusList", analysisStatusList); + + Long analysisList = query.uniqueResult(); + + return analysisList.intValue(); + + } catch (HibernateException e) { + handleException(e, "getAllAnalysisByTestSectionAndStatus"); + } + + return 0; + } + + @Override + public List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber) { + + String sql = "From Analysis a WHERE a.sampleItem.sample.accessionNumber >= :accessionNumber" // + + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // + + " AND a.statusId IN (:analysisStatusList)" // + + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // + + " ORDER BY a.sampleItem.sample.accessionNumber"; // + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("accessionNumber", accessionNumber); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); + + List analysisList = query.list(); + + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getPageAnalysisByStatusFromAccession"); + } + + return null; + } + + @Override + public List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber, String upperRangeAccessionNumber, boolean doRange, + boolean finished) { + + if (finished) { + analysisStatusList.add(Integer + .parseInt(SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.Finalized))); + analysisStatusList.add(Integer.parseInt( + SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.BiologistRejected))); + analysisStatusList.add( + Integer.parseInt(SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.Canceled))); + analysisStatusList.add(Integer + .parseInt(SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.NotStarted))); + analysisStatusList.add(Integer.parseInt( + SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.NonConforming_depricated))); + analysisStatusList.add(Integer + .parseInt(SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.SampleRejected))); + analysisStatusList.add(Integer.parseInt( + SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.TechnicalAcceptance))); + analysisStatusList.add(Integer.parseInt( + SpringContext.getBean(IStatusService.class).getStatusID(AnalysisStatus.TechnicalRejected))); + } + + String sql = ""; + if (doRange && StringUtils.isNotBlank(upperRangeAccessionNumber)) + sql = "From Analysis a WHERE a.sampleItem.sample.accessionNumber between :accessionNumber and" + + " :upperRangeAccessionNumber" // + + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // + + " AND a.statusId IN (:analysisStatusList)" // + + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // + + " ORDER BY a.sampleItem.sample.accessionNumber"; // + else + sql = "From Analysis a WHERE a.sampleItem.sample.accessionNumber = :accessionNumber" // + + " AND length(a.sampleItem.sample.accessionNumber) = length(:accessionNumber)" // + + " AND a.statusId IN (:analysisStatusList)" // + + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)" // + + " ORDER BY a.sampleItem.sample.accessionNumber"; // + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("accessionNumber", accessionNumber); + if (StringUtils.isNotBlank(upperRangeAccessionNumber)) { + query.setParameter("upperRangeAccessionNumber", upperRangeAccessionNumber); + } + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + // query.setMaxResults(SpringContext.getBean(PagingProperties.class).getResultsPageSize()); + + List analysisList = query.list(); + + return analysisList; + + } catch (HibernateException e) { + handleException(e, "getPageAnalysisByStatusFromAccession"); + } + + return null; + } + + @Override + public int getCountAnalysisByStatusFromAccession(List analysisStatusList, List sampleStatusList, + String accessionNumber) { + + String hql = "SELECT COUNT(*) From Analysis a WHERE " + " a.statusId IN (:analysisStatusList)" + + " AND a.sampleItem.sample.statusId IN (:sampleStatusList)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); + query.setParameterList("analysisStatusList", analysisStatusList); + query.setParameterList("sampleStatusList", sampleStatusList); + + Long analysisList = query.uniqueResult(); + + return analysisList.intValue(); + + } catch (HibernateException e) { + handleException(e, "getCountAnalysisByStatusFromAccession"); + } + + return 0; + } + + @Override + public List getAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate) { + String hql = "FROM Analysis a WHERE a.enteredDate BETWEEN :lowerDate AND :upperDate AND" + + " a.sampleItem.sample.id IN (SELECT sr.sampleId FROM SampleRequester sr WHERE" + + " sr.requesterId = :requesterId AND sr.requesterTypeId = (SELECT rt.id FROM" + + " RequesterType rt WHERE rt.requesterType = 'organization' ))"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); + query.setParameter("requesterId", Integer.parseInt(referringSiteId)); + query.setParameter("lowerDate", lowerDate.atStartOfDay()); + query.setParameter("upperDate", upperDate.atTime(LocalTime.MAX)); + return query.list(); + } catch (HibernateException e) { + handleException(e, "getAnalysisForSiteBetweenResultDates"); + } + return new ArrayList<>(); + } + + @Override + public List getStudyAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate) { + String hql = "FROM Analysis a WHERE a.releasedDate BETWEEN :lowerDate AND :upperDate AND" + + " a.sampleItem.sample.id IN (SELECT so.sample.id FROM SampleOrganization so WHERE" + + " so.organization.id = :requesterId )"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Analysis.class); + query.setParameter("requesterId", Integer.parseInt(referringSiteId)); + query.setParameter("lowerDate", lowerDate.atStartOfDay()); + query.setParameter("upperDate", upperDate.atTime(LocalTime.MAX)); + return query.list(); + } catch (HibernateException e) { + handleException(e, "getAnalysisForSiteBetweenResultDates"); + } + return new ArrayList<>(); + } + + @Override + public int getCountOfAnalysesForStatusIds(List statusIdList) { + String hql = "SELECT COUNT(*) From Analysis a WHERE a.statusId IN (:analysisStatusList)"; + try { + Query query = entityManager.unwrap(Session.class).createQuery(hql, Long.class); + query.setParameterList("analysisStatusList", statusIdList); + + Long count = query.uniqueResult(); + return count.intValue(); + + } catch (HibernateException e) { + handleException(e, "getCountOfAnalysesForStatusIds"); + } + + return 0; + } + + @Override + public int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds) { + String sql = "SELECT COUNT(*) From Analysis a where a.releasedDate = :releasedDate and a.statusId in (" + + " :statusList )"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); + query.setParameter("releasedDate", completedDate); + query.setParameterList("statusList", statusIds); + + Long count = query.uniqueResult(); + return count.intValue(); + } catch (HibernateException e) { + handleException(e, "getCountOfAnalysisCompletedOnByStatusId"); + } + + return 0; + } + + @Override + public int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) { + + String sql = "SELECT COUNT(*) from Analysis a where a.startedDate = :startedDate and a.statusId not in (" + + " :statusList )"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); + query.setParameter("startedDate", collectionDate); + query.setParameterList("statusList", statusIds); + + Long count = query.uniqueResult(); + return count.intValue(); + } catch (HibernateException e) { + handleException(e, "getCountOfAnalysisStartedOnExcludedByStatusId"); + } + + return 0; + } + + @Override + public int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds) { + String sql = "SELECT COUNT(*) from Analysis a where a.startedDate = :startedDate and a.statusId in (" + + " :statusList )"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Long.class); + query.setParameter("startedDate", startedDate); + query.setParameterList("statusList", statusIds); + + Long count = query.uniqueResult(); + return count.intValue(); + } catch (HibernateException e) { + handleException(e, "getCountOfAnalysisStartedOnByStatusId"); + } + + return 0; + } + + @Override + public List getAnalysesResultEnteredOnExcludedByStatusId(Date completedDate, Set statusIds) + throws LIMSRuntimeException { + String sql = "from Analysis a where a.completedDate = :completedDate and a.statusId not in ( :statusList" + + " )"; + + try { + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analysis.class); + query.setParameter("completedDate", completedDate); + query.setParameterList("statusList", statusIds); + + List analysisList = query.list(); + return analysisList; + } catch (HibernateException e) { + handleException(e, "getAnalysisResultEnteredOnOnByStatusId"); + } + + return null; + } } diff --git a/src/main/java/org/openelisglobal/analysis/service/AnalysisService.java b/src/main/java/org/openelisglobal/analysis/service/AnalysisService.java index d6d476fb95..434b04bb5a 100644 --- a/src/main/java/org/openelisglobal/analysis/service/AnalysisService.java +++ b/src/main/java/org/openelisglobal/analysis/service/AnalysisService.java @@ -17,225 +17,202 @@ import org.openelisglobal.typeofsample.valueholder.TypeOfSample; public interface AnalysisService extends BaseObjectService { - void getData(Analysis analysis); + void getData(Analysis analysis); - Analysis getAnalysisById(String analysisId); + Analysis getAnalysisById(String analysisId); - List getAnalysisByTestDescriptionAndCompletedDateRange( - List descriptions, Date sqlDayOne, Date sqlDayTwo); + List getAnalysisByTestDescriptionAndCompletedDateRange(List descriptions, Date sqlDayOne, + Date sqlDayTwo); - List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample); + List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample); - List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers); + List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers); - List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample); + List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample); - List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds); + List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds); - List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate); + List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate); - List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange( - Date lowDate, Date highDate, String testId, List testScectionIds); + List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange(Date lowDate, Date highDate, String testId, + List testScectionIds); - List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList); + List getAllAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList); - List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List statusIdList, boolean sortedByDateAndAccession); + List getAllAnalysisByTestSectionAndStatus(String testSectionId, List statusIdList, + boolean sortedByDateAndAccession); - List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem); + List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem); - List getAnalysisByTestNamesAndCompletedDateRange( - List testNames, Date lowDate, Date highDate); + List getAnalysisByTestNamesAndCompletedDateRange(List testNames, Date lowDate, Date highDate); - List getAnalysesBySampleIdTestIdAndStatusId( - List sampleIdList, List testIdList, List statusIdList); + List getAnalysesBySampleIdTestIdAndStatusId(List sampleIdList, List testIdList, + List statusIdList); - List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem); + List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem); - List getAnalysesBySampleItemsExcludingByStatusIds( - SampleItem sampleItem, Set statusIds); + List getAnalysesBySampleItemsExcludingByStatusIds(SampleItem sampleItem, Set statusIds); - List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID); + List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID); - List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem); + List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem); - List getAnalysisCollectedOnExcludedByStatusId( - Date collectionDate, Set statusIds); + List getAnalysisCollectedOnExcludedByStatusId(Date collectionDate, Set statusIds); - Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis); + Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis); - List getAllAnalysisByTestSectionAndExcludedStatus( - String testSectionId, List statusIdList); + List getAllAnalysisByTestSectionAndExcludedStatus(String testSectionId, List statusIdList); - List getAnalysesBySampleStatusIdExcludingByStatusId( - String statusId, Set statusIds); + List getAnalysesBySampleStatusIdExcludingByStatusId(String statusId, Set statusIds); - List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId); + List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String statusId); - List getAnalysisStartedOnExcludedByStatusId( - Date collectionDate, Set statusIds); + List getAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds); - int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds); + int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds); - List getAnalysisByTestSectionAndCompletedDateRange( - String sectionID, Date lowDate, Date highDate); + List getAnalysisByTestSectionAndCompletedDateRange(String sectionID, Date lowDate, Date highDate); - List getMaxRevisionAnalysesReadyToBeReported(); + List getMaxRevisionAnalysesReadyToBeReported(); - void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis); + void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis); - List getAllAnalysisByTestAndExcludedStatus(String testId, List statusIdList); + List getAllAnalysisByTestAndExcludedStatus(String testId, List statusIdList); - List getAnalysesAlreadyReportedBySample(Sample sample); + List getAnalysesAlreadyReportedBySample(Sample sample); - List getRevisionHistoryOfAnalysesBySampleAndTest( - SampleItem sampleItem, Test test, boolean includeLatestRevision); + List getRevisionHistoryOfAnalysesBySampleAndTest(SampleItem sampleItem, Test test, + boolean includeLatestRevision); - List getAnalysesBySampleStatusId(String statusId); + List getAnalysesBySampleStatusId(String statusId); - List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate); + List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate); - List getAnalysesBySampleIdAndStatusId(String id, Set analysisStatusIds); + List getAnalysesBySampleIdAndStatusId(String id, Set analysisStatusIds); - List getAnalysesByPriorityAndStatusId( - OrderPriority priority, List analysisStatusIds); + List getAnalysesByPriorityAndStatusId(OrderPriority priority, List analysisStatusIds); - List getAnalysisStartedOn(Date collectionDate); + List getAnalysisStartedOn(Date collectionDate); - List getMaxRevisionAnalysesBySample(SampleItem sampleItem); + List getMaxRevisionAnalysesBySample(SampleItem sampleItem); - List getAllChildAnalysesByResult(Result result); + List getAllChildAnalysesByResult(Result result); - List getAnalysesBySampleId(String id); + List getAnalysesBySampleId(String id); - List getAnalysesReadyToBeReported(); + List getAnalysesReadyToBeReported(); - List getAnalysisBySampleAndTestIds(String sampleKey, List testIds); + List getAnalysisBySampleAndTestIds(String sampleKey, List testIds); - List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate); + List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate); - List getAnalysesForStatusId(String statusId); + List getAnalysesForStatusId(String statusId); - int getCountOfAnalysesForStatusIds(List statusIdList); + int getCountOfAnalysesForStatusIds(List statusIdList); - List getAllMaxRevisionAnalysesPerTest(Test test); + List getAllMaxRevisionAnalysesPerTest(Test test); - List getAnalysisByAccessionAndTestId(String accessionNumber, String testId); + List getAnalysisByAccessionAndTestId(String accessionNumber, String testId); - List getAnalysisCollectedOn(Date collectionDate); + List getAnalysisCollectedOn(Date collectionDate); - List getAllAnalysisByTestAndStatus(String testId, List statusIdList); + List getAllAnalysisByTestAndStatus(String testId, List statusIdList); - List getAnalysesBySampleItem(SampleItem sampleItem); + List getAnalysesBySampleItem(SampleItem sampleItem); - List getAllAnalysisByTestsAndStatus( - List testIdList, List statusIdList); + List getAllAnalysisByTestsAndStatus(List testIdList, List statusIdList); - Analysis buildAnalysis(Test test, SampleItem sampleItem); + Analysis buildAnalysis(Test test, SampleItem sampleItem); - void updateAnalysises( - List cancelAnalysis, List newAnalysis, String sysUserId); + void updateAnalysises(List cancelAnalysis, List newAnalysis, String sysUserId); - void updateAllNoAuditTrail(List updatedAnalysis); + void updateAllNoAuditTrail(List updatedAnalysis); - void updateNoAuditTrail(Analysis analysis); + void updateNoAuditTrail(Analysis analysis); - String getTestDisplayName(Analysis analysis); + String getTestDisplayName(Analysis analysis); - String getCompletedDateForDisplay(Analysis analysis); + String getCompletedDateForDisplay(Analysis analysis); - String getAnalysisType(Analysis analysis); + String getAnalysisType(Analysis analysis); - String getJSONMultiSelectResults(Analysis analysis); + String getJSONMultiSelectResults(Analysis analysis); - String getCSVMultiselectResults(Analysis analysis); + String getCSVMultiselectResults(Analysis analysis); - Result getQuantifiedResult(Analysis analysis); + Result getQuantifiedResult(Analysis analysis); - String getStatusId(Analysis analysis); + String getStatusId(Analysis analysis); - Boolean getTriggeredReflex(Analysis analysis); + Boolean getTriggeredReflex(Analysis analysis); - boolean resultIsConclusion(Result currentResult, Analysis analysis); + boolean resultIsConclusion(Result currentResult, Analysis analysis); - boolean isParentNonConforming(Analysis analysis); + boolean isParentNonConforming(Analysis analysis); - Test getTest(Analysis analysis); + Test getTest(Analysis analysis); - List getResults(Analysis analysis); + List getResults(Analysis analysis); - boolean hasBeenCorrectedSinceLastPatientReport(Analysis analysis); + boolean hasBeenCorrectedSinceLastPatientReport(Analysis analysis); - boolean patientReportHasBeenDone(Analysis analysis); + boolean patientReportHasBeenDone(Analysis analysis); - String getNotesAsString( - Analysis analysis, - boolean prefixType, - boolean prefixTimestamp, - String noteSeparator, - boolean excludeExternPrefix); + String getNotesAsString(Analysis analysis, boolean prefixType, boolean prefixTimestamp, String noteSeparator, + boolean excludeExternPrefix); - String getOrderAccessionNumber(Analysis analysis); + String getOrderAccessionNumber(Analysis analysis); - TypeOfSample getTypeOfSample(Analysis analysis); + TypeOfSample getTypeOfSample(Analysis analysis); - Panel getPanel(Analysis analysis); + Panel getPanel(Analysis analysis); - TestSection getTestSection(Analysis analysis); + TestSection getTestSection(Analysis analysis); - List getAllAnalysisByTestsAndStatus( - List list, List analysisStatusList, List sampleStatusList); + List getAllAnalysisByTestsAndStatus(List list, List analysisStatusList, + List sampleStatusList); - List get(List value); + List get(List value); - List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List nfsTestIdList, - List analysisStatusList, - List sampleStatusList, - Date lowDate, - Date highDate); + List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List nfsTestIdList, + List analysisStatusList, List sampleStatusList, Date lowDate, Date highDate); - List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList); + List getPageAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList); - int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList); + int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList); - List getPageAnalysisByTestSectionAndStatus( - String sectionId, List statusList, boolean sortedByDateAndAccession); + List getPageAnalysisByTestSectionAndStatus(String sectionId, List statusList, + boolean sortedByDateAndAccession); - List getPageAnalysisAtAccessionNumberAndStatus( - String accessionNumber, List statusList, boolean sortedByDateAndAccession); + List getPageAnalysisAtAccessionNumberAndStatus(String accessionNumber, List statusList, + boolean sortedByDateAndAccession); - int getCountAnalysisByTestSectionAndStatus(String sectionId, List statusList); + int getCountAnalysisByTestSectionAndStatus(String sectionId, List statusList); - int getCountAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber); + int getCountAnalysisByStatusFromAccession(List analysisStatusList, List sampleStatusList, + String accessionNumber); - List getPageAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber); + List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber); - List getPageAnalysisByStatusFromAccession( - List analysisStatusList, - List sampleStatusList, - String accessionNumber, - String upperRangeAccessionNumber, - boolean doRange, - boolean finished); + List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber, String upperRangeAccessionNumber, boolean doRange, + boolean finished); - List getAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate); + List getAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate); - List getStudyAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate); + List getStudyAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate); - List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId); + List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId); - List getAnalysesResultEnteredOnExcludedByStatusId( - Date completedDate, Set statusIds); + List getAnalysesResultEnteredOnExcludedByStatusId(Date completedDate, Set statusIds); - int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds); + int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds); - int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds); + int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds); } diff --git a/src/main/java/org/openelisglobal/analysis/service/AnalysisServiceImpl.java b/src/main/java/org/openelisglobal/analysis/service/AnalysisServiceImpl.java index 0cfc2d6445..eee9445de7 100644 --- a/src/main/java/org/openelisglobal/analysis/service/AnalysisServiceImpl.java +++ b/src/main/java/org/openelisglobal/analysis/service/AnalysisServiceImpl.java @@ -42,789 +42,734 @@ import org.springframework.transaction.annotation.Transactional; @Service -@DependsOn({"springContext"}) -public class AnalysisServiceImpl extends AuditableBaseObjectServiceImpl - implements AnalysisService { - - @Autowired protected AnalysisDAO baseObjectDAO; - @Autowired private DictionaryService dictionaryService; - @Autowired private ResultService resultService; - @Autowired private TypeOfSampleService typeOfSampleService; - @Autowired private ReferenceTablesService referenceTablesService; - @Autowired private NoteService noteService; - - private static String TABLE_REFERENCE_ID; - private final String DEFAULT_ANALYSIS_TYPE = "MANUAL"; - - @PostConstruct - public void initializeGlobalVariables() { - if (TABLE_REFERENCE_ID == null) { - TABLE_REFERENCE_ID = referenceTablesService.getReferenceTableByName("ANALYSIS").getId(); - } - } - - public AnalysisServiceImpl() { - super(Analysis.class); - this.auditTrailLog = true; - } - - public static String getTableReferenceId() { - return TABLE_REFERENCE_ID; - } - - @Override - public String insert(Analysis analysis) { - if (analysis.getFhirUuid() == null) { - analysis.setFhirUuid(UUID.randomUUID()); - } - return super.insert(analysis); - } - - @Override - @Transactional(readOnly = true) - public String getTestDisplayName(Analysis analysis) { - if (analysis == null) { - return ""; - } - Test test = getTest(analysis); - String name = TestServiceImpl.getLocalizedTestNameWithType(test); - if (analysis - .getSampleItem() - .getTypeOfSampleId() - .equals( - SpringContext.getBean(TypeOfSampleService.class) - .getTypeOfSampleIdForLocalAbbreviation("Variable"))) { - name += "(" + analysis.getSampleTypeName() + ")"; - } - - // TypeOfSample typeOfSample = SpringContext.getBean(TypeOfSampleService.class) - // .getTypeOfSampleForTest(test.getId()); - // if (typeOfSample != null && typeOfSample.getId().equals( - // - // SpringContext.getBean(TypeOfSampleService.class).getTypeOfSampleIdForLocalAbbreviation("Variable"))) { - // name += "(" + analysis.getSampleTypeName() + ")"; - // } - - String parentResultType = - analysis.getParentResult() != null ? analysis.getParentResult().getResultType() : ""; - if (TypeOfTestResultServiceImpl.ResultType.isMultiSelectVariant(parentResultType)) { - Dictionary dictionary = - dictionaryService.getDictionaryById(analysis.getParentResult().getValue()); - if (dictionary != null) { - String parentResult = dictionary.getLocalAbbreviation(); - if (GenericValidator.isBlankOrNull(parentResult)) { - parentResult = dictionary.getDictEntry(); +@DependsOn({ "springContext" }) +public class AnalysisServiceImpl extends AuditableBaseObjectServiceImpl implements AnalysisService { + + @Autowired + protected AnalysisDAO baseObjectDAO; + @Autowired + private DictionaryService dictionaryService; + @Autowired + private ResultService resultService; + @Autowired + private TypeOfSampleService typeOfSampleService; + @Autowired + private ReferenceTablesService referenceTablesService; + @Autowired + private NoteService noteService; + + private static String TABLE_REFERENCE_ID; + private final String DEFAULT_ANALYSIS_TYPE = "MANUAL"; + + @PostConstruct + public void initializeGlobalVariables() { + if (TABLE_REFERENCE_ID == null) { + TABLE_REFERENCE_ID = referenceTablesService.getReferenceTableByName("ANALYSIS").getId(); } - name = parentResult + " → " + name; - } - } - - return name; - } - - @Override - @Transactional(readOnly = true) - public String getCSVMultiselectResults(Analysis analysis) { - if (analysis == null) { - return ""; - } - List existingResults = resultService.getResultsByAnalysis(analysis); - StringBuilder multiSelectBuffer = new StringBuilder(); - for (Result existingResult : existingResults) { - if (TypeOfTestResultServiceImpl.ResultType.isMultiSelectVariant( - existingResult.getResultType())) { - multiSelectBuffer.append(existingResult.getValue()); - multiSelectBuffer.append(','); - } - } - - // remove last ',' - multiSelectBuffer.setLength(multiSelectBuffer.length() - 1); - - return multiSelectBuffer.toString(); - } - - @Override - @Transactional(readOnly = true) - public String getJSONMultiSelectResults(Analysis analysis) { - return analysis == null - ? "" - : ResultServiceImpl.getJSONStringForMultiSelect( - resultService.getResultsByAnalysis(analysis)); - } - - @Override - @Transactional(readOnly = true) - public Result getQuantifiedResult(Analysis analysis) { - if (analysis == null) { - return null; - } - List existingResults = resultService.getResultsByAnalysis(analysis); - List quantifiableResultsIds = new ArrayList<>(); - for (Result existingResult : existingResults) { - if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant( - existingResult.getResultType())) { - quantifiableResultsIds.add(existingResult.getId()); - } - } - - for (Result existingResult : existingResults) { - if (!TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant( - existingResult.getResultType()) - && existingResult.getParentResult() != null - && quantifiableResultsIds.contains(existingResult.getParentResult().getId()) - && !GenericValidator.isBlankOrNull(existingResult.getValue())) { - return existingResult; - } - } - - return null; - } - - @Override - @Transactional(readOnly = true) - public String getCompletedDateForDisplay(Analysis analysis) { - return analysis == null ? "" : analysis.getCompletedDateForDisplay(); - } - - @Override - @Transactional(readOnly = true) - public String getAnalysisType(Analysis analysis) { - return analysis == null ? "" : analysis.getAnalysisType(); - } - - @Override - @Transactional(readOnly = true) - public String getStatusId(Analysis analysis) { - return analysis == null ? "" : analysis.getStatusId(); - } - - @Override - @Transactional(readOnly = true) - public Boolean getTriggeredReflex(Analysis analysis) { - return analysis == null ? false : analysis.getTriggeredReflex(); - } - - @Override - public boolean resultIsConclusion(Result currentResult, Analysis analysis) { - if (analysis == null || currentResult == null) { - return false; - } - List results = resultService.getResultsByAnalysis(analysis); - if (results.size() == 1) { - return false; - } - - Long testResultId = Long.parseLong(currentResult.getId()); - // This based on the fact that the conclusion is always added - // after the shared result so if there is a result with a larger id - // then this is not a conclusion - for (Result result : results) { - if (Long.parseLong(result.getId()) > testResultId) { - return false; - } - } - - return true; - } - - @Override - public boolean isParentNonConforming(Analysis analysis) { - return analysis == null ? false : QAService.isAnalysisParentNonConforming(analysis); - } - - @Override - @Transactional(readOnly = true) - public Test getTest(Analysis analysis) { - return analysis == null ? null : analysis.getTest(); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) { - return baseObjectDAO.getAnalysisStartedOrCompletedInDateRange(lowDate, highDate); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange( - Date lowDate, Date highDate, String testId, List testSectionIds) { - return baseObjectDAO.getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange( - lowDate, highDate, testId, testSectionIds); - } - - @Override - @Transactional(readOnly = true) - public List getResults(Analysis analysis) { - return analysis == null ? new ArrayList<>() : resultService.getResultsByAnalysis(analysis); - } - - @Override - public boolean hasBeenCorrectedSinceLastPatientReport(Analysis analysis) { - return analysis == null ? false : analysis.isCorrectedSincePatientReport(); - } - - @Override - public boolean patientReportHasBeenDone(Analysis analysis) { - return analysis == null - ? false - : SpringContext.getBean(IReportTrackingService.class) - .getLastReportForSample( - analysis.getSampleItem().getSample(), ReportTrackingService.ReportType.PATIENT) - != null; - } - - @Override - @Transactional(readOnly = true) - public String getNotesAsString( - Analysis analysis, - boolean prefixType, - boolean prefixTimestamp, - String noteSeparator, - boolean excludeExternPrefix) { - if (analysis == null) { - return ""; - } else { - return noteService.getNotesAsString( - analysis, prefixType, prefixTimestamp, noteSeparator, excludeExternPrefix); - } - } - - @Override - @Transactional(readOnly = true) - public String getOrderAccessionNumber(Analysis analysis) { - return analysis == null ? "" : analysis.getSampleItem().getSample().getAccessionNumber(); - } - - @Override - @Transactional(readOnly = true) - public TypeOfSample getTypeOfSample(Analysis analysis) { - return analysis == null - ? null - : typeOfSampleService.getTypeOfSampleById(analysis.getSampleItem().getTypeOfSampleId()); - } - - @Override - @Transactional(readOnly = true) - public Panel getPanel(Analysis analysis) { - return analysis == null ? null : analysis.getPanel(); - } - - @Override - @Transactional(readOnly = true) - public TestSection getTestSection(Analysis analysis) { - return analysis == null ? null : analysis.getTestSection(); - } - - @Override - public Analysis buildAnalysis(Test test, SampleItem sampleItem) { - - Analysis analysis = new Analysis(); - analysis.setTest(test); - analysis.setIsReportable(test.getIsReportable()); - analysis.setAnalysisType(DEFAULT_ANALYSIS_TYPE); - analysis.setRevision("0"); - analysis.setStartedDate(DateUtil.getNowAsSqlDate()); - analysis.setStatusId( - SpringContext.getBean(IStatusService.class) - .getStatusID(StatusService.AnalysisStatus.NotStarted)); - analysis.setSampleItem(sampleItem); - analysis.setTestSection(test.getTestSection()); - analysis.setSampleTypeName(sampleItem.getTypeOfSample().getLocalizedName()); - - return analysis; - } - - @Override - protected AnalysisDAO getBaseObjectDAO() { - return baseObjectDAO; - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleId(String id) { - return baseObjectDAO.getAnalysesBySampleId(id); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) { - if (accessionNumber != null && accessionNumber.contains(".")) { - accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); - } - return baseObjectDAO.getAnalysisByAccessionAndTestId(accessionNumber, testId); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisCollectedOnExcludedByStatusId( - Date date, Set excludedStatusIds) { - return baseObjectDAO.getAnalysisCollectedOnExcludedByStatusId(date, excludedStatusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItemsExcludingByStatusIds( - SampleItem sampleItem, Set excludedStatusIds) { - return baseObjectDAO.getAnalysesBySampleItemsExcludingByStatusIds( - sampleItem, excludedStatusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesForStatusId(String status) { - return baseObjectDAO.getAllMatching("statusId", status); - } - - @Override - public int getCountOfAnalysesForStatusIds(List statusIdList) { - return baseObjectDAO.getCountOfAnalysesForStatusIds(statusIdList); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleStatusIdExcludingByStatusId( - String sampleStatus, Set excludedStatusIds) { - return baseObjectDAO.getAnalysesBySampleStatusIdExcludingByStatusId( - sampleStatus, excludedStatusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestAndExcludedStatus( - String testId, List excludedStatusIntList) { - return baseObjectDAO.getAllAnalysisByTestAndExcludedStatus(testId, excludedStatusIntList); - } - - @Override - @Transactional - public void updateAnalysises( - List cancelAnalysis, List newAnalysis, String sysUserId) { - String cancelStatus = - SpringContext.getBean(IStatusService.class) - .getStatusID(StatusService.AnalysisStatus.Canceled); - for (Analysis analysis : cancelAnalysis) { - analysis.setStatusId(cancelStatus); - analysis.setSysUserId(sysUserId); - update(analysis); - } - - for (Analysis analysis : newAnalysis) { - analysis.setSysUserId(sysUserId); - insert(analysis); - } - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestAndStatus(String id, List statusList) { - return baseObjectDAO.getAllAnalysisByTestAndStatus(id, statusList); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatusAndCompletedDateRange( - List testIdList, - List analysisStatusList, - List sampleStatusList, - Date lowDate, - Date highDate) { - return baseObjectDAO.getAllAnalysisByTestsAndStatusAndCompletedDateRange( - testIdList, analysisStatusList, sampleStatusList, lowDate, highDate); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndStatus( - String sectionId, List statusList, boolean sortedByDateAndAccession) { - return baseObjectDAO.getAllAnalysisByTestSectionAndStatus( - sectionId, statusList, sortedByDateAndAccession); - } - - @Override - @Transactional(readOnly = true) - public List getPageAnalysisByTestSectionAndStatus( - String sectionId, List statusList, boolean sortedByDateAndAccession) { - return baseObjectDAO.getPageAnalysisByTestSectionAndStatus( - sectionId, statusList, sortedByDateAndAccession); - } - - @Override - @Transactional(readOnly = true) - public List getPageAnalysisAtAccessionNumberAndStatus( - String accessionNumber, List statusList, boolean sortedByDateAndAccession) { - if (accessionNumber != null && accessionNumber.contains(".")) { - accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); - } - return baseObjectDAO.getPageAnalysisAtAccessionNumberAndStatus( - accessionNumber, statusList, sortedByDateAndAccession); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItemIdAndStatusId( - String sampleItemId, String canceledTestStatusId) { - return baseObjectDAO.getAnalysesBySampleItemIdAndStatusId(sampleItemId, canceledTestStatusId); - } - - @Override - @Transactional(readOnly = true) - public void getData(Analysis analysis) { - getBaseObjectDAO().getData(analysis); - } - - @Override - @Transactional(readOnly = true) - public Analysis getAnalysisById(String analysisId) { - return getBaseObjectDAO().getAnalysisById(analysisId); - } - - @Override - public void updateNoAuditTrail(Analysis analysis) { - getBaseObjectDAO().update(analysis); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestDescriptionAndCompletedDateRange( - List descriptions, Date sqlDayOne, Date sqlDayTwo) { - return getBaseObjectDAO() - .getAnalysisByTestDescriptionAndCompletedDateRange(descriptions, sqlDayOne, sqlDayTwo); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) { - return getBaseObjectDAO().getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(sample); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesReadyForReportPreviewBySample( - List accessionNumbers) { - return getBaseObjectDAO().getMaxRevisionAnalysesReadyForReportPreviewBySample(accessionNumbers); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) { - return getBaseObjectDAO().getMaxRevisionPendingAnalysesReadyToBeReportedBySample(sample); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) { - return getBaseObjectDAO().getAnalysesBySampleIdExcludedByStatusId(id, statusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestsAndStatus( - List testIds, List analysisStatusList, List sampleStatusList) { - return getBaseObjectDAO() - .getAllAnalysisByTestsAndStatus(testIds, analysisStatusList, sampleStatusList); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) { - return getBaseObjectDAO() - .getAllAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList, sampleStatusList); - } - - @Override - public List getPageAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) { - return getBaseObjectDAO() - .getPageAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList, sampleStatusList); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) { - return getBaseObjectDAO().getMaxRevisionAnalysesBySampleIncludeCanceled(sampleItem); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestNamesAndCompletedDateRange( - List testNames, Date lowDate, Date highDate) { - return getBaseObjectDAO() - .getAnalysisByTestNamesAndCompletedDateRange(testNames, lowDate, highDate); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdTestIdAndStatusId( - List sampleIdList, List testIdList, List statusIdList) { - return getBaseObjectDAO() - .getAnalysesBySampleIdTestIdAndStatusId(sampleIdList, testIdList, statusIdList); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) { - return getBaseObjectDAO().getMaxRevisionParentTestAnalysesBySample(sampleItem); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOnRangeByStatusId( - Date lowDate, Date highDate, String statusID) { - return getBaseObjectDAO().getAnalysisStartedOnRangeByStatusId(lowDate, highDate, statusID); - } - - @Override - @Transactional(readOnly = true) - public List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) { - return getBaseObjectDAO().getRevisionHistoryOfAnalysesBySample(sampleItem); - } - - @Override - @Transactional(readOnly = true) - public Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) { - return getBaseObjectDAO().getPreviousAnalysisForAmendedAnalysis(analysis); - } - - @Override - @Transactional(readOnly = true) - public List getAllAnalysisByTestSectionAndExcludedStatus( - String testSectionId, List statusIdList) { - return getBaseObjectDAO() - .getAllAnalysisByTestSectionAndExcludedStatus(testSectionId, statusIdList); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOnExcludedByStatusId( - Date collectionDate, Set statusIds) { - return getBaseObjectDAO().getAnalysisStartedOnExcludedByStatusId(collectionDate, statusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisByTestSectionAndCompletedDateRange( - String sectionID, Date lowDate, Date highDate) { - return getBaseObjectDAO() - .getAnalysisByTestSectionAndCompletedDateRange(sectionID, lowDate, highDate); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesReadyToBeReported() { - return getBaseObjectDAO().getMaxRevisionAnalysesReadyToBeReported(); - } - - @Override - @Transactional(readOnly = true) - public void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) { - getBaseObjectDAO().getMaxRevisionAnalysisBySampleAndTest(analysis); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesAlreadyReportedBySample(Sample sample) { - return getBaseObjectDAO().getAnalysesAlreadyReportedBySample(sample); - } - - @Override - @Transactional(readOnly = true) - public List getRevisionHistoryOfAnalysesBySampleAndTest( - SampleItem sampleItem, Test test, boolean includeLatestRevision) { - return getBaseObjectDAO() - .getRevisionHistoryOfAnalysesBySampleAndTest(sampleItem, test, includeLatestRevision); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleStatusId(String statusId) { - return getBaseObjectDAO().getAnalysesBySampleStatusId(statusId); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate) { - return getBaseObjectDAO().getAnalysisEnteredAfterDate(latestCollectionDate); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleIdAndStatusId( - String id, Set analysisStatusIds) { - return getBaseObjectDAO().getAnalysesBySampleIdAndStatusId(id, analysisStatusIds); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisStartedOn(Date collectionDate) { - return getBaseObjectDAO().getAnalysisStartedOn(collectionDate); - } - - @Override - @Transactional(readOnly = true) - public List getMaxRevisionAnalysesBySample(SampleItem sampleItem) { - return getBaseObjectDAO().getMaxRevisionAnalysesBySample(sampleItem); - } - - @Override - @Transactional(readOnly = true) - public List getAllChildAnalysesByResult(Result result) { - return getBaseObjectDAO().getAllChildAnalysesByResult(result); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesReadyToBeReported() { - return getBaseObjectDAO().getAnalysesReadyToBeReported(); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisBySampleAndTestIds(String sampleKey, List testIds) { - return getBaseObjectDAO().getAnalysisBySampleAndTestIds(sampleKey, testIds); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) { - return getBaseObjectDAO().getAnalysisCompleteInRange(lowDate, highDate); - } - - @Override - @Transactional(readOnly = true) - public List getAllMaxRevisionAnalysesPerTest(Test test) { - return getBaseObjectDAO().getAllMaxRevisionAnalysesPerTest(test); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysisCollectedOn(Date collectionDate) { - return getBaseObjectDAO().getAnalysisCollectedOn(collectionDate); - } - - @Override - @Transactional(readOnly = true) - public List getAnalysesBySampleItem(SampleItem sampleItem) { - return getBaseObjectDAO().getAnalysesBySampleItem(sampleItem); - } - - @Override - @Transactional - public void updateAllNoAuditTrail(List updatedAnalysis) { - for (Analysis analysis : updatedAnalysis) { - updateNoAuditTrail(analysis); - } - } - - @Override - public List get(List value) { - return baseObjectDAO.get(value); - } - - @Override - public List getAllAnalysisByTestsAndStatus( - List testIdList, List statusIdList) { - return baseObjectDAO.getAllAnalysisByTestsAndStatus(testIdList, statusIdList); - } - - @Override - public int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList, List sampleStatusList) { - return baseObjectDAO.getCountAnalysisByTestSectionAndStatus( - testSectionId, analysisStatusList, sampleStatusList); - } - - @Override - public int getCountAnalysisByTestSectionAndStatus( - String testSectionId, List analysisStatusList) { - return baseObjectDAO.getCountAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList); - } - - @Override - public int getCountAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber) { - if (accessionNumber != null && accessionNumber.contains(".")) { - accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); - } - return baseObjectDAO.getCountAnalysisByStatusFromAccession( - analysisStatusList, sampleStatusList, accessionNumber); - } - - @Override - public List getPageAnalysisByStatusFromAccession( - List analysisStatusList, List sampleStatusList, String accessionNumber) { - if (accessionNumber != null && accessionNumber.contains(".")) { - accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); - } - return baseObjectDAO.getPageAnalysisByStatusFromAccession( - analysisStatusList, sampleStatusList, accessionNumber); - } - - @Override - public List getPageAnalysisByStatusFromAccession( - List analysisStatusList, - List sampleStatusList, - String accessionNumber, - String upperRangeAccessionNumber, - boolean doRange, - boolean finished) { - if (accessionNumber != null && accessionNumber.contains(".")) { - accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); - } - return baseObjectDAO.getPageAnalysisByStatusFromAccession( - analysisStatusList, - sampleStatusList, - accessionNumber, - upperRangeAccessionNumber, - doRange, - finished); - } - - @Override - public List getAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate) { - return baseObjectDAO.getAnalysisForSiteBetweenResultDates( - referringSiteId, lowerDate, upperDate); - } - - @Override - public List getAnalysesByPriorityAndStatusId( - OrderPriority priority, List analysisStatusIds) { - return baseObjectDAO.getAnalysesByPriorityAndStatusId(priority, analysisStatusIds); - } - - @Override - public List getStudyAnalysisForSiteBetweenResultDates( - String referringSiteId, LocalDate lowerDate, LocalDate upperDate) { - return baseObjectDAO.getStudyAnalysisForSiteBetweenResultDates( - referringSiteId, lowerDate, upperDate); - } - - @Override - public List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) { - return baseObjectDAO.getAnalysesCompletedOnByStatusId(completedDate, statusId); - } - - @Override - public int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds) { - return baseObjectDAO.getCountOfAnalysisCompletedOnByStatusId(completedDate, statusIds); - } - - @Override - public int getCountOfAnalysisStartedOnExcludedByStatusId( - Date collectionDate, Set statusIds) { - return baseObjectDAO.getCountOfAnalysisStartedOnExcludedByStatusId(collectionDate, statusIds); - } - - @Override - public int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds) { - return baseObjectDAO.getCountOfAnalysisStartedOnByStatusId(startedDate, statusIds); - } - - @Override - public List getAnalysesResultEnteredOnExcludedByStatusId( - Date completedDate, Set statusIds) { - return baseObjectDAO.getAnalysesResultEnteredOnExcludedByStatusId(completedDate, statusIds); - } + } + + public AnalysisServiceImpl() { + super(Analysis.class); + this.auditTrailLog = true; + } + + public static String getTableReferenceId() { + return TABLE_REFERENCE_ID; + } + + @Override + public String insert(Analysis analysis) { + if (analysis.getFhirUuid() == null) { + analysis.setFhirUuid(UUID.randomUUID()); + } + return super.insert(analysis); + } + + @Override + @Transactional(readOnly = true) + public String getTestDisplayName(Analysis analysis) { + if (analysis == null) { + return ""; + } + Test test = getTest(analysis); + String name = TestServiceImpl.getLocalizedTestNameWithType(test); + if (analysis.getSampleItem().getTypeOfSampleId().equals( + SpringContext.getBean(TypeOfSampleService.class).getTypeOfSampleIdForLocalAbbreviation("Variable"))) { + name += "(" + analysis.getSampleTypeName() + ")"; + } + + // TypeOfSample typeOfSample = SpringContext.getBean(TypeOfSampleService.class) + // .getTypeOfSampleForTest(test.getId()); + // if (typeOfSample != null && typeOfSample.getId().equals( + // + // SpringContext.getBean(TypeOfSampleService.class).getTypeOfSampleIdForLocalAbbreviation("Variable"))) + // { + // name += "(" + analysis.getSampleTypeName() + ")"; + // } + + String parentResultType = analysis.getParentResult() != null ? analysis.getParentResult().getResultType() : ""; + if (TypeOfTestResultServiceImpl.ResultType.isMultiSelectVariant(parentResultType)) { + Dictionary dictionary = dictionaryService.getDictionaryById(analysis.getParentResult().getValue()); + if (dictionary != null) { + String parentResult = dictionary.getLocalAbbreviation(); + if (GenericValidator.isBlankOrNull(parentResult)) { + parentResult = dictionary.getDictEntry(); + } + name = parentResult + " → " + name; + } + } + + return name; + } + + @Override + @Transactional(readOnly = true) + public String getCSVMultiselectResults(Analysis analysis) { + if (analysis == null) { + return ""; + } + List existingResults = resultService.getResultsByAnalysis(analysis); + StringBuilder multiSelectBuffer = new StringBuilder(); + for (Result existingResult : existingResults) { + if (TypeOfTestResultServiceImpl.ResultType.isMultiSelectVariant(existingResult.getResultType())) { + multiSelectBuffer.append(existingResult.getValue()); + multiSelectBuffer.append(','); + } + } + + // remove last ',' + multiSelectBuffer.setLength(multiSelectBuffer.length() - 1); + + return multiSelectBuffer.toString(); + } + + @Override + @Transactional(readOnly = true) + public String getJSONMultiSelectResults(Analysis analysis) { + return analysis == null ? "" + : ResultServiceImpl.getJSONStringForMultiSelect(resultService.getResultsByAnalysis(analysis)); + } + + @Override + @Transactional(readOnly = true) + public Result getQuantifiedResult(Analysis analysis) { + if (analysis == null) { + return null; + } + List existingResults = resultService.getResultsByAnalysis(analysis); + List quantifiableResultsIds = new ArrayList<>(); + for (Result existingResult : existingResults) { + if (TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(existingResult.getResultType())) { + quantifiableResultsIds.add(existingResult.getId()); + } + } + + for (Result existingResult : existingResults) { + if (!TypeOfTestResultServiceImpl.ResultType.isDictionaryVariant(existingResult.getResultType()) + && existingResult.getParentResult() != null + && quantifiableResultsIds.contains(existingResult.getParentResult().getId()) + && !GenericValidator.isBlankOrNull(existingResult.getValue())) { + return existingResult; + } + } + + return null; + } + + @Override + @Transactional(readOnly = true) + public String getCompletedDateForDisplay(Analysis analysis) { + return analysis == null ? "" : analysis.getCompletedDateForDisplay(); + } + + @Override + @Transactional(readOnly = true) + public String getAnalysisType(Analysis analysis) { + return analysis == null ? "" : analysis.getAnalysisType(); + } + + @Override + @Transactional(readOnly = true) + public String getStatusId(Analysis analysis) { + return analysis == null ? "" : analysis.getStatusId(); + } + + @Override + @Transactional(readOnly = true) + public Boolean getTriggeredReflex(Analysis analysis) { + return analysis == null ? false : analysis.getTriggeredReflex(); + } + + @Override + public boolean resultIsConclusion(Result currentResult, Analysis analysis) { + if (analysis == null || currentResult == null) { + return false; + } + List results = resultService.getResultsByAnalysis(analysis); + if (results.size() == 1) { + return false; + } + + Long testResultId = Long.parseLong(currentResult.getId()); + // This based on the fact that the conclusion is always added + // after the shared result so if there is a result with a larger id + // then this is not a conclusion + for (Result result : results) { + if (Long.parseLong(result.getId()) > testResultId) { + return false; + } + } + + return true; + } + + @Override + public boolean isParentNonConforming(Analysis analysis) { + return analysis == null ? false : QAService.isAnalysisParentNonConforming(analysis); + } + + @Override + @Transactional(readOnly = true) + public Test getTest(Analysis analysis) { + return analysis == null ? null : analysis.getTest(); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOrCompletedInDateRange(Date lowDate, Date highDate) { + return baseObjectDAO.getAnalysisStartedOrCompletedInDateRange(lowDate, highDate); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange(Date lowDate, Date highDate, + String testId, List testSectionIds) { + return baseObjectDAO.getAnalysisByTestIdAndTestSectionIdsAndStartedInDateRange(lowDate, highDate, testId, + testSectionIds); + } + + @Override + @Transactional(readOnly = true) + public List getResults(Analysis analysis) { + return analysis == null ? new ArrayList<>() : resultService.getResultsByAnalysis(analysis); + } + + @Override + public boolean hasBeenCorrectedSinceLastPatientReport(Analysis analysis) { + return analysis == null ? false : analysis.isCorrectedSincePatientReport(); + } + + @Override + public boolean patientReportHasBeenDone(Analysis analysis) { + return analysis == null ? false + : SpringContext.getBean(IReportTrackingService.class).getLastReportForSample( + analysis.getSampleItem().getSample(), ReportTrackingService.ReportType.PATIENT) != null; + } + + @Override + @Transactional(readOnly = true) + public String getNotesAsString(Analysis analysis, boolean prefixType, boolean prefixTimestamp, String noteSeparator, + boolean excludeExternPrefix) { + if (analysis == null) { + return ""; + } else { + return noteService.getNotesAsString(analysis, prefixType, prefixTimestamp, noteSeparator, + excludeExternPrefix); + } + } + + @Override + @Transactional(readOnly = true) + public String getOrderAccessionNumber(Analysis analysis) { + return analysis == null ? "" : analysis.getSampleItem().getSample().getAccessionNumber(); + } + + @Override + @Transactional(readOnly = true) + public TypeOfSample getTypeOfSample(Analysis analysis) { + return analysis == null ? null + : typeOfSampleService.getTypeOfSampleById(analysis.getSampleItem().getTypeOfSampleId()); + } + + @Override + @Transactional(readOnly = true) + public Panel getPanel(Analysis analysis) { + return analysis == null ? null : analysis.getPanel(); + } + + @Override + @Transactional(readOnly = true) + public TestSection getTestSection(Analysis analysis) { + return analysis == null ? null : analysis.getTestSection(); + } + + @Override + public Analysis buildAnalysis(Test test, SampleItem sampleItem) { + + Analysis analysis = new Analysis(); + analysis.setTest(test); + analysis.setIsReportable(test.getIsReportable()); + analysis.setAnalysisType(DEFAULT_ANALYSIS_TYPE); + analysis.setRevision("0"); + analysis.setStartedDate(DateUtil.getNowAsSqlDate()); + analysis.setStatusId( + SpringContext.getBean(IStatusService.class).getStatusID(StatusService.AnalysisStatus.NotStarted)); + analysis.setSampleItem(sampleItem); + analysis.setTestSection(test.getTestSection()); + analysis.setSampleTypeName(sampleItem.getTypeOfSample().getLocalizedName()); + + return analysis; + } + + @Override + protected AnalysisDAO getBaseObjectDAO() { + return baseObjectDAO; + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleId(String id) { + return baseObjectDAO.getAnalysesBySampleId(id); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByAccessionAndTestId(String accessionNumber, String testId) { + if (accessionNumber != null && accessionNumber.contains(".")) { + accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); + } + return baseObjectDAO.getAnalysisByAccessionAndTestId(accessionNumber, testId); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisCollectedOnExcludedByStatusId(Date date, Set excludedStatusIds) { + return baseObjectDAO.getAnalysisCollectedOnExcludedByStatusId(date, excludedStatusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItemsExcludingByStatusIds(SampleItem sampleItem, + Set excludedStatusIds) { + return baseObjectDAO.getAnalysesBySampleItemsExcludingByStatusIds(sampleItem, excludedStatusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesForStatusId(String status) { + return baseObjectDAO.getAllMatching("statusId", status); + } + + @Override + public int getCountOfAnalysesForStatusIds(List statusIdList) { + return baseObjectDAO.getCountOfAnalysesForStatusIds(statusIdList); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleStatusIdExcludingByStatusId(String sampleStatus, + Set excludedStatusIds) { + return baseObjectDAO.getAnalysesBySampleStatusIdExcludingByStatusId(sampleStatus, excludedStatusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestAndExcludedStatus(String testId, List excludedStatusIntList) { + return baseObjectDAO.getAllAnalysisByTestAndExcludedStatus(testId, excludedStatusIntList); + } + + @Override + @Transactional + public void updateAnalysises(List cancelAnalysis, List newAnalysis, String sysUserId) { + String cancelStatus = SpringContext.getBean(IStatusService.class) + .getStatusID(StatusService.AnalysisStatus.Canceled); + for (Analysis analysis : cancelAnalysis) { + analysis.setStatusId(cancelStatus); + analysis.setSysUserId(sysUserId); + update(analysis); + } + + for (Analysis analysis : newAnalysis) { + analysis.setSysUserId(sysUserId); + insert(analysis); + } + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestAndStatus(String id, List statusList) { + return baseObjectDAO.getAllAnalysisByTestAndStatus(id, statusList); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatusAndCompletedDateRange(List testIdList, + List analysisStatusList, List sampleStatusList, Date lowDate, Date highDate) { + return baseObjectDAO.getAllAnalysisByTestsAndStatusAndCompletedDateRange(testIdList, analysisStatusList, + sampleStatusList, lowDate, highDate); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndStatus(String sectionId, List statusList, + boolean sortedByDateAndAccession) { + return baseObjectDAO.getAllAnalysisByTestSectionAndStatus(sectionId, statusList, sortedByDateAndAccession); + } + + @Override + @Transactional(readOnly = true) + public List getPageAnalysisByTestSectionAndStatus(String sectionId, List statusList, + boolean sortedByDateAndAccession) { + return baseObjectDAO.getPageAnalysisByTestSectionAndStatus(sectionId, statusList, sortedByDateAndAccession); + } + + @Override + @Transactional(readOnly = true) + public List getPageAnalysisAtAccessionNumberAndStatus(String accessionNumber, List statusList, + boolean sortedByDateAndAccession) { + if (accessionNumber != null && accessionNumber.contains(".")) { + accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); + } + return baseObjectDAO.getPageAnalysisAtAccessionNumberAndStatus(accessionNumber, statusList, + sortedByDateAndAccession); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItemIdAndStatusId(String sampleItemId, String canceledTestStatusId) { + return baseObjectDAO.getAnalysesBySampleItemIdAndStatusId(sampleItemId, canceledTestStatusId); + } + + @Override + @Transactional(readOnly = true) + public void getData(Analysis analysis) { + getBaseObjectDAO().getData(analysis); + } + + @Override + @Transactional(readOnly = true) + public Analysis getAnalysisById(String analysisId) { + return getBaseObjectDAO().getAnalysisById(analysisId); + } + + @Override + public void updateNoAuditTrail(Analysis analysis) { + getBaseObjectDAO().update(analysis); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestDescriptionAndCompletedDateRange(List descriptions, Date sqlDayOne, + Date sqlDayTwo) { + return getBaseObjectDAO().getAnalysisByTestDescriptionAndCompletedDateRange(descriptions, sqlDayOne, sqlDayTwo); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(Sample sample) { + return getBaseObjectDAO().getMaxRevisionPendingAnalysesReadyForReportPreviewBySample(sample); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesReadyForReportPreviewBySample(List accessionNumbers) { + return getBaseObjectDAO().getMaxRevisionAnalysesReadyForReportPreviewBySample(accessionNumbers); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionPendingAnalysesReadyToBeReportedBySample(Sample sample) { + return getBaseObjectDAO().getMaxRevisionPendingAnalysesReadyToBeReportedBySample(sample); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdExcludedByStatusId(String id, Set statusIds) { + return getBaseObjectDAO().getAnalysesBySampleIdExcludedByStatusId(id, statusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestsAndStatus(List testIds, List analysisStatusList, + List sampleStatusList) { + return getBaseObjectDAO().getAllAnalysisByTestsAndStatus(testIds, analysisStatusList, sampleStatusList); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) { + return getBaseObjectDAO().getAllAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList, + sampleStatusList); + } + + @Override + public List getPageAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) { + return getBaseObjectDAO().getPageAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList, + sampleStatusList); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesBySampleIncludeCanceled(SampleItem sampleItem) { + return getBaseObjectDAO().getMaxRevisionAnalysesBySampleIncludeCanceled(sampleItem); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestNamesAndCompletedDateRange(List testNames, Date lowDate, + Date highDate) { + return getBaseObjectDAO().getAnalysisByTestNamesAndCompletedDateRange(testNames, lowDate, highDate); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdTestIdAndStatusId(List sampleIdList, List testIdList, + List statusIdList) { + return getBaseObjectDAO().getAnalysesBySampleIdTestIdAndStatusId(sampleIdList, testIdList, statusIdList); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionParentTestAnalysesBySample(SampleItem sampleItem) { + return getBaseObjectDAO().getMaxRevisionParentTestAnalysesBySample(sampleItem); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOnRangeByStatusId(Date lowDate, Date highDate, String statusID) { + return getBaseObjectDAO().getAnalysisStartedOnRangeByStatusId(lowDate, highDate, statusID); + } + + @Override + @Transactional(readOnly = true) + public List getRevisionHistoryOfAnalysesBySample(SampleItem sampleItem) { + return getBaseObjectDAO().getRevisionHistoryOfAnalysesBySample(sampleItem); + } + + @Override + @Transactional(readOnly = true) + public Analysis getPreviousAnalysisForAmendedAnalysis(Analysis analysis) { + return getBaseObjectDAO().getPreviousAnalysisForAmendedAnalysis(analysis); + } + + @Override + @Transactional(readOnly = true) + public List getAllAnalysisByTestSectionAndExcludedStatus(String testSectionId, + List statusIdList) { + return getBaseObjectDAO().getAllAnalysisByTestSectionAndExcludedStatus(testSectionId, statusIdList); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) { + return getBaseObjectDAO().getAnalysisStartedOnExcludedByStatusId(collectionDate, statusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisByTestSectionAndCompletedDateRange(String sectionID, Date lowDate, Date highDate) { + return getBaseObjectDAO().getAnalysisByTestSectionAndCompletedDateRange(sectionID, lowDate, highDate); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesReadyToBeReported() { + return getBaseObjectDAO().getMaxRevisionAnalysesReadyToBeReported(); + } + + @Override + @Transactional(readOnly = true) + public void getMaxRevisionAnalysisBySampleAndTest(Analysis analysis) { + getBaseObjectDAO().getMaxRevisionAnalysisBySampleAndTest(analysis); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesAlreadyReportedBySample(Sample sample) { + return getBaseObjectDAO().getAnalysesAlreadyReportedBySample(sample); + } + + @Override + @Transactional(readOnly = true) + public List getRevisionHistoryOfAnalysesBySampleAndTest(SampleItem sampleItem, Test test, + boolean includeLatestRevision) { + return getBaseObjectDAO().getRevisionHistoryOfAnalysesBySampleAndTest(sampleItem, test, includeLatestRevision); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleStatusId(String statusId) { + return getBaseObjectDAO().getAnalysesBySampleStatusId(statusId); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisEnteredAfterDate(Timestamp latestCollectionDate) { + return getBaseObjectDAO().getAnalysisEnteredAfterDate(latestCollectionDate); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleIdAndStatusId(String id, Set analysisStatusIds) { + return getBaseObjectDAO().getAnalysesBySampleIdAndStatusId(id, analysisStatusIds); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisStartedOn(Date collectionDate) { + return getBaseObjectDAO().getAnalysisStartedOn(collectionDate); + } + + @Override + @Transactional(readOnly = true) + public List getMaxRevisionAnalysesBySample(SampleItem sampleItem) { + return getBaseObjectDAO().getMaxRevisionAnalysesBySample(sampleItem); + } + + @Override + @Transactional(readOnly = true) + public List getAllChildAnalysesByResult(Result result) { + return getBaseObjectDAO().getAllChildAnalysesByResult(result); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesReadyToBeReported() { + return getBaseObjectDAO().getAnalysesReadyToBeReported(); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisBySampleAndTestIds(String sampleKey, List testIds) { + return getBaseObjectDAO().getAnalysisBySampleAndTestIds(sampleKey, testIds); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisCompleteInRange(Timestamp lowDate, Timestamp highDate) { + return getBaseObjectDAO().getAnalysisCompleteInRange(lowDate, highDate); + } + + @Override + @Transactional(readOnly = true) + public List getAllMaxRevisionAnalysesPerTest(Test test) { + return getBaseObjectDAO().getAllMaxRevisionAnalysesPerTest(test); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysisCollectedOn(Date collectionDate) { + return getBaseObjectDAO().getAnalysisCollectedOn(collectionDate); + } + + @Override + @Transactional(readOnly = true) + public List getAnalysesBySampleItem(SampleItem sampleItem) { + return getBaseObjectDAO().getAnalysesBySampleItem(sampleItem); + } + + @Override + @Transactional + public void updateAllNoAuditTrail(List updatedAnalysis) { + for (Analysis analysis : updatedAnalysis) { + updateNoAuditTrail(analysis); + } + } + + @Override + public List get(List value) { + return baseObjectDAO.get(value); + } + + @Override + public List getAllAnalysisByTestsAndStatus(List testIdList, List statusIdList) { + return baseObjectDAO.getAllAnalysisByTestsAndStatus(testIdList, statusIdList); + } + + @Override + public int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList, + List sampleStatusList) { + return baseObjectDAO.getCountAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList, + sampleStatusList); + } + + @Override + public int getCountAnalysisByTestSectionAndStatus(String testSectionId, List analysisStatusList) { + return baseObjectDAO.getCountAnalysisByTestSectionAndStatus(testSectionId, analysisStatusList); + } + + @Override + public int getCountAnalysisByStatusFromAccession(List analysisStatusList, List sampleStatusList, + String accessionNumber) { + if (accessionNumber != null && accessionNumber.contains(".")) { + accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); + } + return baseObjectDAO.getCountAnalysisByStatusFromAccession(analysisStatusList, sampleStatusList, + accessionNumber); + } + + @Override + public List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber) { + if (accessionNumber != null && accessionNumber.contains(".")) { + accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); + } + return baseObjectDAO.getPageAnalysisByStatusFromAccession(analysisStatusList, sampleStatusList, + accessionNumber); + } + + @Override + public List getPageAnalysisByStatusFromAccession(List analysisStatusList, + List sampleStatusList, String accessionNumber, String upperRangeAccessionNumber, boolean doRange, + boolean finished) { + if (accessionNumber != null && accessionNumber.contains(".")) { + accessionNumber = accessionNumber.substring(0, accessionNumber.indexOf('.')); + } + return baseObjectDAO.getPageAnalysisByStatusFromAccession(analysisStatusList, sampleStatusList, accessionNumber, + upperRangeAccessionNumber, doRange, finished); + } + + @Override + public List getAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate) { + return baseObjectDAO.getAnalysisForSiteBetweenResultDates(referringSiteId, lowerDate, upperDate); + } + + @Override + public List getAnalysesByPriorityAndStatusId(OrderPriority priority, List analysisStatusIds) { + return baseObjectDAO.getAnalysesByPriorityAndStatusId(priority, analysisStatusIds); + } + + @Override + public List getStudyAnalysisForSiteBetweenResultDates(String referringSiteId, LocalDate lowerDate, + LocalDate upperDate) { + return baseObjectDAO.getStudyAnalysisForSiteBetweenResultDates(referringSiteId, lowerDate, upperDate); + } + + @Override + public List getAnalysesCompletedOnByStatusId(Date completedDate, String statusId) { + return baseObjectDAO.getAnalysesCompletedOnByStatusId(completedDate, statusId); + } + + @Override + public int getCountOfAnalysisCompletedOnByStatusId(Date completedDate, List statusIds) { + return baseObjectDAO.getCountOfAnalysisCompletedOnByStatusId(completedDate, statusIds); + } + + @Override + public int getCountOfAnalysisStartedOnExcludedByStatusId(Date collectionDate, Set statusIds) { + return baseObjectDAO.getCountOfAnalysisStartedOnExcludedByStatusId(collectionDate, statusIds); + } + + @Override + public int getCountOfAnalysisStartedOnByStatusId(Date startedDate, List statusIds) { + return baseObjectDAO.getCountOfAnalysisStartedOnByStatusId(startedDate, statusIds); + } + + @Override + public List getAnalysesResultEnteredOnExcludedByStatusId(Date completedDate, Set statusIds) { + return baseObjectDAO.getAnalysesResultEnteredOnExcludedByStatusId(completedDate, statusIds); + } } diff --git a/src/main/java/org/openelisglobal/analysis/valueholder/Analysis.java b/src/main/java/org/openelisglobal/analysis/valueholder/Analysis.java index b0e64fbfaa..14b4f9ce77 100644 --- a/src/main/java/org/openelisglobal/analysis/valueholder/Analysis.java +++ b/src/main/java/org/openelisglobal/analysis/valueholder/Analysis.java @@ -36,467 +36,465 @@ public class Analysis extends BaseObject implements NoteObject { - private static final long serialVersionUID = 1L; - - private String id; - private UUID fhirUuid; - private ValueHolderInterface sampleItem; - private String analysisType; - private ValueHolderInterface testSection; - private String testSectionName; - private ValueHolderInterface test; - private String testName; - private String revision; - private String status; - private Date startedDate = null; - private String startedDateForDisplay = null; - private Date completedDate = null; - private Timestamp enteredDate = null; - private String completedDateForDisplay = null; - private Date releasedDate = null; - private String releasedDateForDisplay = null; - private Date printedDate = null; - private String printedDateForDisplay = null; - private String isReportable; - private Date soSendReadyDate = null; - private String soSendReadyDateForDisplay = null; - private String soClientReference; - private Date soNotifyReceivedDate = null; - private String soNotifyReceivedDateForDisplay = null; - private Date soNotifySendDate = null; - private String soNotifySendDateForDisplay = null; - private Date soSendDate = null; - private String soSendDateForDisplay = null; - private String soSendEntryBy; - private Date soSendEntryDate = null; - private String soSendEntryDateForDisplay = null; - private ValueHolderInterface parentAnalysis; - private ValueHolderInterface parentResult; - private ValueHolderInterface panel; - private Boolean triggeredReflex = false; - private Boolean resultCalculated = false; - private String statusId; - private String assignedSortedTestTreeDisplayValue; - private boolean referredOut = false; - private String sampleTypeName; - private List children; - private boolean correctedSincePatientReport; - - public Analysis() { - super(); - sampleItem = new ValueHolder(); - testSection = new ValueHolder(); - test = new ValueHolder(); - parentAnalysis = new ValueHolder(); - parentResult = new ValueHolder(); - panel = new ValueHolder(); - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public String getId() { - return id; - } - - public String getSampleTypeName() { - return sampleTypeName; - } - - public void setSampleTypeName(String sampleTypeName) { - this.sampleTypeName = sampleTypeName; - } - - public String getAssignedSortedTestTreeDisplayValue() { - return assignedSortedTestTreeDisplayValue; - } - - public List getChildren() { - return children; - } - - public void setChildren(List children) { - this.children = children; - } - - public void setAssignedSortedTestTreeDisplayValue(String assignedSortedTestTreeDisplayValue) { - this.assignedSortedTestTreeDisplayValue = assignedSortedTestTreeDisplayValue; - } - - public String getAnalysisType() { - return analysisType; - } - - public void setAnalysisType(String analysisType) { - this.analysisType = analysisType; - } - - public SampleItem getSampleItem() { - return (SampleItem) sampleItem.getValue(); - } - - public void setSampleItem(SampleItem sampleItem) { - this.sampleItem.setValue(sampleItem); - - if (GenericValidator.isBlankOrNull(sampleTypeName) - && sampleItem != null - && sampleItem.getTypeOfSample() != null) { - setSampleTypeName(sampleItem.getTypeOfSample().getLocalizedName()); - } - } - - public Date getCompletedDate() { - return completedDate; - } - - public void setCompletedDate(Date completedDate) { - this.completedDate = completedDate; - completedDateForDisplay = DateUtil.convertSqlDateToStringDate(completedDate); - } - - public String getCompletedDateForDisplay() { - return completedDateForDisplay; - } - - public void setCompletedDateForDisplay(String completedDateForDisplay) { - this.completedDateForDisplay = completedDateForDisplay; - - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - completedDate = DateUtil.convertStringDateToSqlDate(this.completedDateForDisplay, locale); - } - - public String getRevision() { - return revision; - } - - public void setRevision(String revision) { - this.revision = revision; - } - - public Date getStartedDate() { - return startedDate; - } - - public void setStartedDate(Date startedDate) { - this.startedDate = startedDate; - startedDateForDisplay = DateUtil.convertSqlDateToStringDate(startedDate); - } - - public String getStartedDateForDisplay() { - return startedDateForDisplay; - } - - public void setStartedDateForDisplay(String startedDateForDisplay) { - this.startedDateForDisplay = startedDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - startedDate = DateUtil.convertStringDateToSqlDate(this.startedDateForDisplay, locale); - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getIsReportable() { - return isReportable; - } - - public void setIsReportable(String isReportable) { - this.isReportable = isReportable; - } - - public Date getPrintedDate() { - return printedDate; - } - - public void setPrintedDate(Date printedDate) { - this.printedDate = printedDate; - printedDateForDisplay = DateUtil.convertSqlDateToStringDate(printedDate); - } - - public String getPrintedDateForDisplay() { - return printedDateForDisplay; - } - - public void setPrintedDateForDisplay(String printedDateForDisplay) { - this.printedDateForDisplay = printedDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - printedDate = DateUtil.convertStringDateToSqlDate(this.printedDateForDisplay, locale); - } - - public Date getReleasedDate() { - return releasedDate; - } - - public void setReleasedDate(Date releasedDate) { - this.releasedDate = releasedDate; - releasedDateForDisplay = DateUtil.convertSqlDateToStringDate(releasedDate); - } - - public String getReleasedDateForDisplay() { - return releasedDateForDisplay; - } - - public void setReleasedDateForDisplay(String releasedDateForDisplay) { - this.releasedDateForDisplay = releasedDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - releasedDate = DateUtil.convertStringDateToSqlDate(this.releasedDateForDisplay, locale); - } - - public String getSoClientReference() { - return soClientReference; - } - - public void setSoClientReference(String soClientReference) { - this.soClientReference = soClientReference; - } - - public Date getSoNotifyReceivedDate() { - return soNotifyReceivedDate; - } - - public void setSoNotifyReceivedDate(Date soNotifyReceivedDate) { - this.soNotifyReceivedDate = soNotifyReceivedDate; - soNotifyReceivedDateForDisplay = DateUtil.convertSqlDateToStringDate(soNotifyReceivedDate); - } - - public String getSoNotifyReceivedDateForDisplay() { - return soNotifyReceivedDateForDisplay; - } - - public void setSoNotifyReceivedDateForDisplay(String soNotifyReceivedDateForDisplay) { - this.soNotifyReceivedDateForDisplay = soNotifyReceivedDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - soNotifyReceivedDate = - DateUtil.convertStringDateToSqlDate(this.soNotifyReceivedDateForDisplay, locale); - } - - public Date getSoNotifySendDate() { - return soNotifySendDate; - } - - public void setSoNotifySendDate(Date soNotifySendDate) { - this.soNotifySendDate = soNotifySendDate; - soNotifySendDateForDisplay = DateUtil.convertSqlDateToStringDate(soNotifySendDate); - } - - public String getSoNotifySendDateForDisplay() { - return soNotifySendDateForDisplay; - } - - public void setSoNotifySendDateForDisplay(String soNotifySendDateForDisplay) { - this.soNotifySendDateForDisplay = soNotifySendDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - soNotifySendDate = DateUtil.convertStringDateToSqlDate(this.soNotifySendDateForDisplay, locale); - } - - public Date getSoSendDate() { - return soSendDate; - } - - public void setSoSendDate(Date soSendDate) { - this.soSendDate = soSendDate; - soSendDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendDate); - } - - public String getSoSendDateForDisplay() { - return soSendDateForDisplay; - } - - public void setSoSendDateForDisplay(String soSendDateForDisplay) { - this.soSendDateForDisplay = soSendDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - soSendDate = DateUtil.convertStringDateToSqlDate(this.soSendDateForDisplay, locale); - } - - public String getSoSendEntryBy() { - return soSendEntryBy; - } - - public void setSoSendEntryBy(String soSendEntryBy) { - this.soSendEntryBy = soSendEntryBy; - } - - public Date getSoSendEntryDate() { - return soSendEntryDate; - } - - public void setSoSendEntryDate(Date soSendEntryDate) { - this.soSendEntryDate = soSendEntryDate; - soSendEntryDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendEntryDate); - } - - public String getSoSendEntryDateForDisplay() { - return soSendEntryDateForDisplay; - } - - public void setSoSendEntryDateForDisplay(String soSendEntryDateForDisplay) { - this.soSendEntryDateForDisplay = soSendEntryDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - soSendEntryDate = DateUtil.convertStringDateToSqlDate(this.soSendEntryDateForDisplay, locale); - } - - public Date getSoSendReadyDate() { - return soSendReadyDate; - } - - public void setSoSendReadyDate(Date soSendReadyDate) { - this.soSendReadyDate = soSendReadyDate; - soSendReadyDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendReadyDate); - } - - public String getSoSendReadyDateForDisplay() { - return soSendReadyDateForDisplay; - } - - public void setSoSendReadyDateForDisplay(String soSendReadyDateForDisplay) { - this.soSendReadyDateForDisplay = soSendReadyDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - soSendReadyDate = DateUtil.convertStringDateToSqlDate(this.soSendReadyDateForDisplay, locale); - } - - public TestSection getTestSection() { - return (TestSection) testSection.getValue(); - } - - public void setTestSection(TestSection testSection) { - this.testSection.setValue(testSection); - } - - public Test getTest() { - return (Test) test.getValue(); - } - - public void setTest(Test test) { - this.test.setValue(test); - } - - public String getTestSectionName() { - return testSectionName; - } - - public void setTestSectionName(String testSectionName) { - this.testSectionName = testSectionName; - } - - public String getTestName() { - return testName; - } - - public void setTestName(String testName) { - this.testName = testName; - } - - public Analysis getParentAnalysis() { - return (Analysis) parentAnalysis.getValue(); - } - - public void setParentAnalysis(Analysis parentAnalysis) { - this.parentAnalysis.setValue(parentAnalysis); - } - - public Result getParentResult() { - return (Result) parentResult.getValue(); - } - - public void setParentResult(Result parentResult) { - this.parentResult.setValue(parentResult); - } - - public void setTriggeredReflex(Boolean triggeredReflex) { - this.triggeredReflex = triggeredReflex; - } - - public Boolean getTriggeredReflex() { - return triggeredReflex; - } - - public Boolean getResultCalculated() { - return resultCalculated; - } - - public void setResultCalculated(Boolean resultCalculated) { - this.resultCalculated = resultCalculated; - } - - public void setStatusId(String statusId) { - this.statusId = statusId; - } - - public String getStatusId() { - return statusId; - } - - public void setEnteredDate(Timestamp enteredDate) { - this.enteredDate = enteredDate; - } - - public Timestamp getEnteredDate() { - return enteredDate; - } - - public Panel getPanel() { - return (Panel) panel.getValue(); - } - - public void setPanel(Panel panel) { - this.panel.setValue(panel); - } - - public boolean isReferredOut() { - return referredOut; - } - - public void setReferredOut(boolean referredOut) { - this.referredOut = referredOut; - } - - public boolean isCorrectedSincePatientReport() { - return correctedSincePatientReport; - } + private static final long serialVersionUID = 1L; + + private String id; + private UUID fhirUuid; + private ValueHolderInterface sampleItem; + private String analysisType; + private ValueHolderInterface testSection; + private String testSectionName; + private ValueHolderInterface test; + private String testName; + private String revision; + private String status; + private Date startedDate = null; + private String startedDateForDisplay = null; + private Date completedDate = null; + private Timestamp enteredDate = null; + private String completedDateForDisplay = null; + private Date releasedDate = null; + private String releasedDateForDisplay = null; + private Date printedDate = null; + private String printedDateForDisplay = null; + private String isReportable; + private Date soSendReadyDate = null; + private String soSendReadyDateForDisplay = null; + private String soClientReference; + private Date soNotifyReceivedDate = null; + private String soNotifyReceivedDateForDisplay = null; + private Date soNotifySendDate = null; + private String soNotifySendDateForDisplay = null; + private Date soSendDate = null; + private String soSendDateForDisplay = null; + private String soSendEntryBy; + private Date soSendEntryDate = null; + private String soSendEntryDateForDisplay = null; + private ValueHolderInterface parentAnalysis; + private ValueHolderInterface parentResult; + private ValueHolderInterface panel; + private Boolean triggeredReflex = false; + private Boolean resultCalculated = false; + private String statusId; + private String assignedSortedTestTreeDisplayValue; + private boolean referredOut = false; + private String sampleTypeName; + private List children; + private boolean correctedSincePatientReport; + + public Analysis() { + super(); + sampleItem = new ValueHolder(); + testSection = new ValueHolder(); + test = new ValueHolder(); + parentAnalysis = new ValueHolder(); + parentResult = new ValueHolder(); + panel = new ValueHolder(); + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public String getId() { + return id; + } + + public String getSampleTypeName() { + return sampleTypeName; + } + + public void setSampleTypeName(String sampleTypeName) { + this.sampleTypeName = sampleTypeName; + } + + public String getAssignedSortedTestTreeDisplayValue() { + return assignedSortedTestTreeDisplayValue; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public void setAssignedSortedTestTreeDisplayValue(String assignedSortedTestTreeDisplayValue) { + this.assignedSortedTestTreeDisplayValue = assignedSortedTestTreeDisplayValue; + } + + public String getAnalysisType() { + return analysisType; + } + + public void setAnalysisType(String analysisType) { + this.analysisType = analysisType; + } + + public SampleItem getSampleItem() { + return (SampleItem) sampleItem.getValue(); + } - public void setCorrectedSincePatientReport(boolean correctedSincePatientReport) { - this.correctedSincePatientReport = correctedSincePatientReport; - } + public void setSampleItem(SampleItem sampleItem) { + this.sampleItem.setValue(sampleItem); + + if (GenericValidator.isBlankOrNull(sampleTypeName) && sampleItem != null + && sampleItem.getTypeOfSample() != null) { + setSampleTypeName(sampleItem.getTypeOfSample().getLocalizedName()); + } + } + + public Date getCompletedDate() { + return completedDate; + } + + public void setCompletedDate(Date completedDate) { + this.completedDate = completedDate; + completedDateForDisplay = DateUtil.convertSqlDateToStringDate(completedDate); + } + + public String getCompletedDateForDisplay() { + return completedDateForDisplay; + } + + public void setCompletedDateForDisplay(String completedDateForDisplay) { + this.completedDateForDisplay = completedDateForDisplay; + + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + completedDate = DateUtil.convertStringDateToSqlDate(this.completedDateForDisplay, locale); + } + + public String getRevision() { + return revision; + } + + public void setRevision(String revision) { + this.revision = revision; + } + + public Date getStartedDate() { + return startedDate; + } + + public void setStartedDate(Date startedDate) { + this.startedDate = startedDate; + startedDateForDisplay = DateUtil.convertSqlDateToStringDate(startedDate); + } + + public String getStartedDateForDisplay() { + return startedDateForDisplay; + } + + public void setStartedDateForDisplay(String startedDateForDisplay) { + this.startedDateForDisplay = startedDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + startedDate = DateUtil.convertStringDateToSqlDate(this.startedDateForDisplay, locale); + } - @Override - public String getTableId() { - return AnalysisServiceImpl.getTableReferenceId(); - } - - @Override - public String getObjectId() { - return getId(); - } - - @Override - public BoundTo getBoundTo() { - return BoundTo.ANALYSIS; - } - - public String getFhirUuidAsString() { - return fhirUuid == null ? "" : fhirUuid.toString(); - } - - public UUID getFhirUuid() { - return fhirUuid; - } - - public void setFhirUuid(UUID fhirUuid) { - this.fhirUuid = fhirUuid; - } + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getIsReportable() { + return isReportable; + } + + public void setIsReportable(String isReportable) { + this.isReportable = isReportable; + } + + public Date getPrintedDate() { + return printedDate; + } + + public void setPrintedDate(Date printedDate) { + this.printedDate = printedDate; + printedDateForDisplay = DateUtil.convertSqlDateToStringDate(printedDate); + } + + public String getPrintedDateForDisplay() { + return printedDateForDisplay; + } + + public void setPrintedDateForDisplay(String printedDateForDisplay) { + this.printedDateForDisplay = printedDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + printedDate = DateUtil.convertStringDateToSqlDate(this.printedDateForDisplay, locale); + } + + public Date getReleasedDate() { + return releasedDate; + } + + public void setReleasedDate(Date releasedDate) { + this.releasedDate = releasedDate; + releasedDateForDisplay = DateUtil.convertSqlDateToStringDate(releasedDate); + } + + public String getReleasedDateForDisplay() { + return releasedDateForDisplay; + } + + public void setReleasedDateForDisplay(String releasedDateForDisplay) { + this.releasedDateForDisplay = releasedDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + releasedDate = DateUtil.convertStringDateToSqlDate(this.releasedDateForDisplay, locale); + } + + public String getSoClientReference() { + return soClientReference; + } + + public void setSoClientReference(String soClientReference) { + this.soClientReference = soClientReference; + } + + public Date getSoNotifyReceivedDate() { + return soNotifyReceivedDate; + } + + public void setSoNotifyReceivedDate(Date soNotifyReceivedDate) { + this.soNotifyReceivedDate = soNotifyReceivedDate; + soNotifyReceivedDateForDisplay = DateUtil.convertSqlDateToStringDate(soNotifyReceivedDate); + } + + public String getSoNotifyReceivedDateForDisplay() { + return soNotifyReceivedDateForDisplay; + } + + public void setSoNotifyReceivedDateForDisplay(String soNotifyReceivedDateForDisplay) { + this.soNotifyReceivedDateForDisplay = soNotifyReceivedDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + soNotifyReceivedDate = DateUtil.convertStringDateToSqlDate(this.soNotifyReceivedDateForDisplay, locale); + } + + public Date getSoNotifySendDate() { + return soNotifySendDate; + } + + public void setSoNotifySendDate(Date soNotifySendDate) { + this.soNotifySendDate = soNotifySendDate; + soNotifySendDateForDisplay = DateUtil.convertSqlDateToStringDate(soNotifySendDate); + } + + public String getSoNotifySendDateForDisplay() { + return soNotifySendDateForDisplay; + } + + public void setSoNotifySendDateForDisplay(String soNotifySendDateForDisplay) { + this.soNotifySendDateForDisplay = soNotifySendDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + soNotifySendDate = DateUtil.convertStringDateToSqlDate(this.soNotifySendDateForDisplay, locale); + } + + public Date getSoSendDate() { + return soSendDate; + } + + public void setSoSendDate(Date soSendDate) { + this.soSendDate = soSendDate; + soSendDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendDate); + } + + public String getSoSendDateForDisplay() { + return soSendDateForDisplay; + } + + public void setSoSendDateForDisplay(String soSendDateForDisplay) { + this.soSendDateForDisplay = soSendDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + soSendDate = DateUtil.convertStringDateToSqlDate(this.soSendDateForDisplay, locale); + } + + public String getSoSendEntryBy() { + return soSendEntryBy; + } + + public void setSoSendEntryBy(String soSendEntryBy) { + this.soSendEntryBy = soSendEntryBy; + } + + public Date getSoSendEntryDate() { + return soSendEntryDate; + } + + public void setSoSendEntryDate(Date soSendEntryDate) { + this.soSendEntryDate = soSendEntryDate; + soSendEntryDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendEntryDate); + } + + public String getSoSendEntryDateForDisplay() { + return soSendEntryDateForDisplay; + } + + public void setSoSendEntryDateForDisplay(String soSendEntryDateForDisplay) { + this.soSendEntryDateForDisplay = soSendEntryDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + soSendEntryDate = DateUtil.convertStringDateToSqlDate(this.soSendEntryDateForDisplay, locale); + } + + public Date getSoSendReadyDate() { + return soSendReadyDate; + } + + public void setSoSendReadyDate(Date soSendReadyDate) { + this.soSendReadyDate = soSendReadyDate; + soSendReadyDateForDisplay = DateUtil.convertSqlDateToStringDate(soSendReadyDate); + } + + public String getSoSendReadyDateForDisplay() { + return soSendReadyDateForDisplay; + } + + public void setSoSendReadyDateForDisplay(String soSendReadyDateForDisplay) { + this.soSendReadyDateForDisplay = soSendReadyDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + soSendReadyDate = DateUtil.convertStringDateToSqlDate(this.soSendReadyDateForDisplay, locale); + } + + public TestSection getTestSection() { + return (TestSection) testSection.getValue(); + } + + public void setTestSection(TestSection testSection) { + this.testSection.setValue(testSection); + } + + public Test getTest() { + return (Test) test.getValue(); + } + + public void setTest(Test test) { + this.test.setValue(test); + } + + public String getTestSectionName() { + return testSectionName; + } + + public void setTestSectionName(String testSectionName) { + this.testSectionName = testSectionName; + } + + public String getTestName() { + return testName; + } + + public void setTestName(String testName) { + this.testName = testName; + } + + public Analysis getParentAnalysis() { + return (Analysis) parentAnalysis.getValue(); + } + + public void setParentAnalysis(Analysis parentAnalysis) { + this.parentAnalysis.setValue(parentAnalysis); + } + + public Result getParentResult() { + return (Result) parentResult.getValue(); + } + + public void setParentResult(Result parentResult) { + this.parentResult.setValue(parentResult); + } + + public void setTriggeredReflex(Boolean triggeredReflex) { + this.triggeredReflex = triggeredReflex; + } + + public Boolean getTriggeredReflex() { + return triggeredReflex; + } + + public Boolean getResultCalculated() { + return resultCalculated; + } + + public void setResultCalculated(Boolean resultCalculated) { + this.resultCalculated = resultCalculated; + } + + public void setStatusId(String statusId) { + this.statusId = statusId; + } + + public String getStatusId() { + return statusId; + } + + public void setEnteredDate(Timestamp enteredDate) { + this.enteredDate = enteredDate; + } + + public Timestamp getEnteredDate() { + return enteredDate; + } + + public Panel getPanel() { + return (Panel) panel.getValue(); + } + + public void setPanel(Panel panel) { + this.panel.setValue(panel); + } + + public boolean isReferredOut() { + return referredOut; + } + + public void setReferredOut(boolean referredOut) { + this.referredOut = referredOut; + } + + public boolean isCorrectedSincePatientReport() { + return correctedSincePatientReport; + } + + public void setCorrectedSincePatientReport(boolean correctedSincePatientReport) { + this.correctedSincePatientReport = correctedSincePatientReport; + } + + @Override + public String getTableId() { + return AnalysisServiceImpl.getTableReferenceId(); + } + + @Override + public String getObjectId() { + return getId(); + } + + @Override + public BoundTo getBoundTo() { + return BoundTo.ANALYSIS; + } + + public String getFhirUuidAsString() { + return fhirUuid == null ? "" : fhirUuid.toString(); + } + + public UUID getFhirUuid() { + return fhirUuid; + } + + public void setFhirUuid(UUID fhirUuid) { + this.fhirUuid = fhirUuid; + } } diff --git a/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAO.java b/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAO.java index 16825b98a7..af6bd20aec 100644 --- a/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAO.java +++ b/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAO.java @@ -3,4 +3,5 @@ import org.openelisglobal.analysisqaevent.valueholder.AnalysisQaEvent; import org.openelisglobal.common.dao.BaseDAO; -public interface AnalysisQaEventDAO extends BaseDAO {} +public interface AnalysisQaEventDAO extends BaseDAO { +} diff --git a/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAOImpl.java b/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAOImpl.java index b8806ad632..2d7f1aee61 100644 --- a/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAOImpl.java +++ b/src/main/java/org/openelisglobal/analysisqaevent/dao/AnalysisQaEventDAOImpl.java @@ -7,9 +7,8 @@ @Component @Transactional -public class AnalysisQaEventDAOImpl extends BaseDAOImpl - implements AnalysisQaEventDAO { - AnalysisQaEventDAOImpl() { - super(AnalysisQaEvent.class); - } +public class AnalysisQaEventDAOImpl extends BaseDAOImpl implements AnalysisQaEventDAO { + AnalysisQaEventDAOImpl() { + super(AnalysisQaEvent.class); + } } diff --git a/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventService.java b/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventService.java index 263afb0b76..f045283787 100644 --- a/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventService.java +++ b/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventService.java @@ -3,4 +3,5 @@ import org.openelisglobal.analysisqaevent.valueholder.AnalysisQaEvent; import org.openelisglobal.common.service.BaseObjectService; -public interface AnalysisQaEventService extends BaseObjectService {} +public interface AnalysisQaEventService extends BaseObjectService { +} diff --git a/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventServiceImpl.java b/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventServiceImpl.java index cf0285f9c3..c642ec7904 100644 --- a/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventServiceImpl.java +++ b/src/main/java/org/openelisglobal/analysisqaevent/service/AnalysisQaEventServiceImpl.java @@ -7,17 +7,17 @@ import org.springframework.stereotype.Service; @Service -public class AnalysisQaEventServiceImpl - extends AuditableBaseObjectServiceImpl - implements AnalysisQaEventService { - @Autowired protected AnalysisQaEventDAO baseObjectDAO; +public class AnalysisQaEventServiceImpl extends AuditableBaseObjectServiceImpl + implements AnalysisQaEventService { + @Autowired + protected AnalysisQaEventDAO baseObjectDAO; - AnalysisQaEventServiceImpl() { - super(AnalysisQaEvent.class); - } + AnalysisQaEventServiceImpl() { + super(AnalysisQaEvent.class); + } - @Override - protected AnalysisQaEventDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected AnalysisQaEventDAO getBaseObjectDAO() { + return baseObjectDAO; + } } diff --git a/src/main/java/org/openelisglobal/analysisqaevent/valueholder/AnalysisQaEvent.java b/src/main/java/org/openelisglobal/analysisqaevent/valueholder/AnalysisQaEvent.java index 46a346c2ef..468785c914 100644 --- a/src/main/java/org/openelisglobal/analysisqaevent/valueholder/AnalysisQaEvent.java +++ b/src/main/java/org/openelisglobal/analysisqaevent/valueholder/AnalysisQaEvent.java @@ -24,124 +24,124 @@ public class AnalysisQaEvent extends BaseObject { - private String id; + private String id; - private String qaEventId; + private String qaEventId; - private ValueHolderInterface qaEvent; + private ValueHolderInterface qaEvent; - private String analysisId; + private String analysisId; - private ValueHolderInterface analysis; + private ValueHolderInterface analysis; - private Date completedDate; + private Date completedDate; - private String completedDateForDisplay; + private String completedDateForDisplay; - private String analysisQaEventDisplayValue; + private String analysisQaEventDisplayValue; - public AnalysisQaEvent() { - super(); - this.analysis = new ValueHolder(); - this.qaEvent = new ValueHolder(); - } + public AnalysisQaEvent() { + super(); + this.analysis = new ValueHolder(); + this.qaEvent = new ValueHolder(); + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - // ANALYSIS - public Analysis getAnalysis() { - return (Analysis) this.analysis.getValue(); - } + // ANALYSIS + public Analysis getAnalysis() { + return (Analysis) this.analysis.getValue(); + } - public void setAnalysis(ValueHolderInterface analysis) { - this.analysis = analysis; - } + public void setAnalysis(ValueHolderInterface analysis) { + this.analysis = analysis; + } - public void setAnalysis(Analysis analysis) { - this.analysis.setValue(analysis); - } + public void setAnalysis(Analysis analysis) { + this.analysis.setValue(analysis); + } - protected ValueHolderInterface getAnalysisHolder() { - return this.analysis; - } + protected ValueHolderInterface getAnalysisHolder() { + return this.analysis; + } - protected void setAnalysisHolder(ValueHolderInterface analysis) { - this.analysis = analysis; - } + protected void setAnalysisHolder(ValueHolderInterface analysis) { + this.analysis = analysis; + } - // QA_EVENT - public QaEvent getQaEvent() { - return (QaEvent) this.qaEvent.getValue(); - } + // QA_EVENT + public QaEvent getQaEvent() { + return (QaEvent) this.qaEvent.getValue(); + } - public void setQaEvent(ValueHolderInterface qaEvent) { - this.qaEvent = qaEvent; - } + public void setQaEvent(ValueHolderInterface qaEvent) { + this.qaEvent = qaEvent; + } - public void setQaEvent(QaEvent qaEvent) { - this.qaEvent.setValue(qaEvent); - } + public void setQaEvent(QaEvent qaEvent) { + this.qaEvent.setValue(qaEvent); + } - protected ValueHolderInterface getQaEventHolder() { - return this.qaEvent; - } + protected ValueHolderInterface getQaEventHolder() { + return this.qaEvent; + } - protected void setQaEventHolder(ValueHolderInterface qaEvent) { - this.qaEvent = qaEvent; - } + protected void setQaEventHolder(ValueHolderInterface qaEvent) { + this.qaEvent = qaEvent; + } - public String getAnalysisId() { - return analysisId; - } + public String getAnalysisId() { + return analysisId; + } - public void setAnalysisId(String analysisId) { - this.analysisId = analysisId; - } + public void setAnalysisId(String analysisId) { + this.analysisId = analysisId; + } - public Date getCompletedDate() { - return completedDate; - } + public Date getCompletedDate() { + return completedDate; + } - public void setCompletedDate(Date completedDate) { - this.completedDate = completedDate; - this.completedDateForDisplay = DateUtil.convertSqlDateToStringDate(completedDate); - } + public void setCompletedDate(Date completedDate) { + this.completedDate = completedDate; + this.completedDateForDisplay = DateUtil.convertSqlDateToStringDate(completedDate); + } - public String getCompletedDateForDisplay() { - return completedDateForDisplay; - } + public String getCompletedDateForDisplay() { + return completedDateForDisplay; + } - public void setCompletedDateForDisplay(String completedDateForDisplay) { - this.completedDateForDisplay = completedDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - this.completedDate = DateUtil.convertStringDateToSqlDate(completedDateForDisplay, locale); - } + public void setCompletedDateForDisplay(String completedDateForDisplay) { + this.completedDateForDisplay = completedDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + this.completedDate = DateUtil.convertStringDateToSqlDate(completedDateForDisplay, locale); + } - public String getQaEventId() { - return qaEventId; - } + public String getQaEventId() { + return qaEventId; + } - public void setQaEventId(String qaEventId) { - this.qaEventId = qaEventId; - } - - public String getAnalysisQaEventDisplayValue() { - if (analysis != null && qaEvent != null) { - Analysis analysis = getAnalysis(); - String testDisplayValue = analysis.getTest().getTestDisplayValue(); - QaEvent qaEvent = getQaEvent(); - String qaEventDisplayValue = qaEvent.getQaEventDisplayValue(); - analysisQaEventDisplayValue = testDisplayValue + " | " + qaEventDisplayValue; - } else { - analysisQaEventDisplayValue = "NO VALUES AVAILABLE"; - } - return analysisQaEventDisplayValue; - } + public void setQaEventId(String qaEventId) { + this.qaEventId = qaEventId; + } + + public String getAnalysisQaEventDisplayValue() { + if (analysis != null && qaEvent != null) { + Analysis analysis = getAnalysis(); + String testDisplayValue = analysis.getTest().getTestDisplayValue(); + QaEvent qaEvent = getQaEvent(); + String qaEventDisplayValue = qaEvent.getQaEventDisplayValue(); + analysisQaEventDisplayValue = testDisplayValue + " | " + qaEventDisplayValue; + } else { + analysisQaEventDisplayValue = "NO VALUES AVAILABLE"; + } + return analysisQaEventDisplayValue; + } } diff --git a/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAO.java b/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAO.java index e7c8b31e20..68adfaecf3 100644 --- a/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAO.java +++ b/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAO.java @@ -3,4 +3,5 @@ import org.openelisglobal.analysisqaeventaction.valueholder.AnalysisQaEventAction; import org.openelisglobal.common.dao.BaseDAO; -public interface AnalysisQaEventActionDAO extends BaseDAO {} +public interface AnalysisQaEventActionDAO extends BaseDAO { +} diff --git a/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAOImpl.java b/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAOImpl.java index 1739bd80bf..cb34a54304 100644 --- a/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAOImpl.java +++ b/src/main/java/org/openelisglobal/analysisqaeventaction/dao/AnalysisQaEventActionDAOImpl.java @@ -8,8 +8,8 @@ @Component @Transactional public class AnalysisQaEventActionDAOImpl extends BaseDAOImpl - implements AnalysisQaEventActionDAO { - AnalysisQaEventActionDAOImpl() { - super(AnalysisQaEventAction.class); - } + implements AnalysisQaEventActionDAO { + AnalysisQaEventActionDAOImpl() { + super(AnalysisQaEventAction.class); + } } diff --git a/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionService.java b/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionService.java index 95da6e8fc5..dc2e7a5b91 100644 --- a/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionService.java +++ b/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionService.java @@ -3,5 +3,5 @@ import org.openelisglobal.analysisqaeventaction.valueholder.AnalysisQaEventAction; import org.openelisglobal.common.service.BaseObjectService; -public interface AnalysisQaEventActionService - extends BaseObjectService {} +public interface AnalysisQaEventActionService extends BaseObjectService { +} diff --git a/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionServiceImpl.java b/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionServiceImpl.java index 25de902525..0be61d2e9b 100644 --- a/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionServiceImpl.java +++ b/src/main/java/org/openelisglobal/analysisqaeventaction/service/AnalysisQaEventActionServiceImpl.java @@ -7,17 +7,17 @@ import org.springframework.stereotype.Service; @Service -public class AnalysisQaEventActionServiceImpl - extends AuditableBaseObjectServiceImpl - implements AnalysisQaEventActionService { - @Autowired protected AnalysisQaEventActionDAO baseObjectDAO; +public class AnalysisQaEventActionServiceImpl extends AuditableBaseObjectServiceImpl + implements AnalysisQaEventActionService { + @Autowired + protected AnalysisQaEventActionDAO baseObjectDAO; - AnalysisQaEventActionServiceImpl() { - super(AnalysisQaEventAction.class); - } + AnalysisQaEventActionServiceImpl() { + super(AnalysisQaEventAction.class); + } - @Override - protected AnalysisQaEventActionDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected AnalysisQaEventActionDAO getBaseObjectDAO() { + return baseObjectDAO; + } } diff --git a/src/main/java/org/openelisglobal/analysisqaeventaction/valueholder/AnalysisQaEventAction.java b/src/main/java/org/openelisglobal/analysisqaeventaction/valueholder/AnalysisQaEventAction.java index 7f48019287..9a81b36f47 100644 --- a/src/main/java/org/openelisglobal/analysisqaeventaction/valueholder/AnalysisQaEventAction.java +++ b/src/main/java/org/openelisglobal/analysisqaeventaction/valueholder/AnalysisQaEventAction.java @@ -25,130 +25,130 @@ public class AnalysisQaEventAction extends BaseObject { - private String id; + private String id; - private String analysisQaEventId; + private String analysisQaEventId; - private ValueHolderInterface analysisQaEvent; + private ValueHolderInterface analysisQaEvent; - private String actionId; + private String actionId; - private ValueHolderInterface action; + private ValueHolderInterface action; - private Date createdDate; + private Date createdDate; - private String createdDateForDisplay; + private String createdDateForDisplay; - // bugzilla 2481 - private SystemUser systemUser; + // bugzilla 2481 + private SystemUser systemUser; - private String systemUserId; + private String systemUserId; - public AnalysisQaEventAction() { - super(); - this.action = new ValueHolder(); - this.analysisQaEvent = new ValueHolder(); - } + public AnalysisQaEventAction() { + super(); + this.action = new ValueHolder(); + this.analysisQaEvent = new ValueHolder(); + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - // Action - public Action getAction() { - return (Action) this.action.getValue(); - } + // Action + public Action getAction() { + return (Action) this.action.getValue(); + } - public void setAction(ValueHolderInterface action) { - this.action = action; - } + public void setAction(ValueHolderInterface action) { + this.action = action; + } - public void setAction(Action action) { - this.action.setValue(action); - } + public void setAction(Action action) { + this.action.setValue(action); + } - protected ValueHolderInterface getActionHolder() { - return this.action; - } + protected ValueHolderInterface getActionHolder() { + return this.action; + } - protected void setActionHolder(ValueHolderInterface action) { - this.action = action; - } + protected void setActionHolder(ValueHolderInterface action) { + this.action = action; + } - // ANALYSIS_QA_EVENT - public AnalysisQaEvent getAnalysisQaEvent() { - return (AnalysisQaEvent) this.analysisQaEvent.getValue(); - } + // ANALYSIS_QA_EVENT + public AnalysisQaEvent getAnalysisQaEvent() { + return (AnalysisQaEvent) this.analysisQaEvent.getValue(); + } - public void setAnalysisQaEvent(ValueHolderInterface analysisQaEvent) { - this.analysisQaEvent = analysisQaEvent; - } + public void setAnalysisQaEvent(ValueHolderInterface analysisQaEvent) { + this.analysisQaEvent = analysisQaEvent; + } - public void setAnalysisQaEvent(AnalysisQaEvent analysisQaEvent) { - this.analysisQaEvent.setValue(analysisQaEvent); - } + public void setAnalysisQaEvent(AnalysisQaEvent analysisQaEvent) { + this.analysisQaEvent.setValue(analysisQaEvent); + } - protected ValueHolderInterface getAnalysisQaEventHolder() { - return this.analysisQaEvent; - } + protected ValueHolderInterface getAnalysisQaEventHolder() { + return this.analysisQaEvent; + } - protected void setAnalysisQaEventHolder(ValueHolderInterface analysisQaEvent) { - this.analysisQaEvent = analysisQaEvent; - } + protected void setAnalysisQaEventHolder(ValueHolderInterface analysisQaEvent) { + this.analysisQaEvent = analysisQaEvent; + } - public String getActionId() { - return actionId; - } + public String getActionId() { + return actionId; + } - public void setActionId(String actionId) { - this.actionId = actionId; - } + public void setActionId(String actionId) { + this.actionId = actionId; + } - public Date getCreatedDate() { - return createdDate; - } + public Date getCreatedDate() { + return createdDate; + } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - this.createdDateForDisplay = DateUtil.convertSqlDateToStringDate(createdDate); - } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + this.createdDateForDisplay = DateUtil.convertSqlDateToStringDate(createdDate); + } - public String getCreatedDateForDisplay() { - return this.createdDateForDisplay; - } + public String getCreatedDateForDisplay() { + return this.createdDateForDisplay; + } - public void setCreatedDateForDisplay(String createdDateForDisplay) { - this.createdDateForDisplay = createdDateForDisplay; - // also update the java.sql.Date - String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); - this.createdDate = DateUtil.convertStringDateToSqlDate(createdDateForDisplay, locale); - } + public void setCreatedDateForDisplay(String createdDateForDisplay) { + this.createdDateForDisplay = createdDateForDisplay; + // also update the java.sql.Date + String locale = SystemConfiguration.getInstance().getDefaultLocale().toString(); + this.createdDate = DateUtil.convertStringDateToSqlDate(createdDateForDisplay, locale); + } - public String getAnalysisQaEventId() { - return analysisQaEventId; - } + public String getAnalysisQaEventId() { + return analysisQaEventId; + } - public void setAnalysisQaEventId(String analysisQaEventId) { - this.analysisQaEventId = analysisQaEventId; - } - - public void setSystemUser(SystemUser systemUser) { - this.systemUser = systemUser; - } - - public SystemUser getSystemUser() { - return this.systemUser; - } - - public String getSystemUserId() { - return systemUserId; - } - - public void setSystemUserId(String systemUserId) { - this.systemUserId = systemUserId; - } + public void setAnalysisQaEventId(String analysisQaEventId) { + this.analysisQaEventId = analysisQaEventId; + } + + public void setSystemUser(SystemUser systemUser) { + this.systemUser = systemUser; + } + + public SystemUser getSystemUser() { + return this.systemUser; + } + + public String getSystemUserId() { + return systemUserId; + } + + public void setSystemUserId(String systemUserId) { + this.systemUserId = systemUserId; + } } diff --git a/src/main/java/org/openelisglobal/analyte/dao/AnalyteDAO.java b/src/main/java/org/openelisglobal/analyte/dao/AnalyteDAO.java index 3d53e5d23f..fc6280ff0b 100644 --- a/src/main/java/org/openelisglobal/analyte/dao/AnalyteDAO.java +++ b/src/main/java/org/openelisglobal/analyte/dao/AnalyteDAO.java @@ -19,41 +19,45 @@ /** * @author diane benz - *

To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>Templates. To enable and disable the creation of type comments go to - * Window>Preferences>Java>Code Generation. + *

+ * To change this generated comment edit the template variable + * "typecomment": Window>Preferences>Java>Templates. To enable and + * disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. */ public interface AnalyteDAO extends BaseDAO { - // public boolean insertData(Analyte analyte) throws LIMSRuntimeException; + // public boolean insertData(Analyte analyte) throws LIMSRuntimeException; - // public void deleteData(List analytes) throws LIMSRuntimeException; + // public void deleteData(List analytes) throws LIMSRuntimeException; - // public List getAllAnalytes() throws LIMSRuntimeException; + // public List getAllAnalytes() throws LIMSRuntimeException; - // public List getPageOfAnalytes(int startingRecNo) throws LIMSRuntimeException; + // public List getPageOfAnalytes(int startingRecNo) throws LIMSRuntimeException; - // public void getData(Analyte analyte) throws LIMSRuntimeException; + // public void getData(Analyte analyte) throws LIMSRuntimeException; - // public void updateData(Analyte analyte) throws LIMSRuntimeException; + // public void updateData(Analyte analyte) throws LIMSRuntimeException; - // public List getAnalytes(String filter) throws LIMSRuntimeException; + // public List getAnalytes(String filter) throws LIMSRuntimeException; - // + // - // bugzilla 1367 added boolean param - public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) throws LIMSRuntimeException; + // bugzilla 1367 added boolean param + public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) throws LIMSRuntimeException; - boolean duplicateAnalyteExists(Analyte analyte); + boolean duplicateAnalyteExists(Analyte analyte); - // bugzilla 1411 - // public Integer getTotalAnalyteCount() throws LIMSRuntimeException; + // bugzilla 1411 + // public Integer getTotalAnalyteCount() throws LIMSRuntimeException; - // bugzilla 2370 - // public List getPagesOfSearchedAnalytes(int startRecNo, String searchString) throws - // LIMSRuntimeException; + // bugzilla 2370 + // public List getPagesOfSearchedAnalytes(int startRecNo, String searchString) + // throws + // LIMSRuntimeException; - // bugzilla 2370 - // public Integer getTotalSearchedAnalyteCount(String searchString) throws LIMSRuntimeException; + // bugzilla 2370 + // public Integer getTotalSearchedAnalyteCount(String searchString) throws + // LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/analyte/daoimpl/AnalyteDAOImpl.java b/src/main/java/org/openelisglobal/analyte/daoimpl/AnalyteDAOImpl.java index cbb4ddda78..8a12701ede 100644 --- a/src/main/java/org/openelisglobal/analyte/daoimpl/AnalyteDAOImpl.java +++ b/src/main/java/org/openelisglobal/analyte/daoimpl/AnalyteDAOImpl.java @@ -35,91 +35,89 @@ @Transactional public class AnalyteDAOImpl extends BaseDAOImpl implements AnalyteDAO { - public AnalyteDAOImpl() { - super(Analyte.class); - } - - @Override - public void delete(Analyte analyte) { - LogEvent.logWarn( - this.getClass().getSimpleName(), "delete", "delete analyte is not implemented"); - } - - // bugzilla 1367 added ignoreCase - @Override - @Transactional(readOnly = true) - public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) throws LIMSRuntimeException { - try { - - String sql = null; - if (ignoreCase) { - sql = "from Analyte a where trim(lower(a.analyteName)) = :param and a.isActive='Y'"; - - } else { - sql = "from Analyte a where a.analyteName = :param and a.isActive='Y'"; - } - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analyte.class); - - if (ignoreCase) { - query.setParameter("param", analyte.getAnalyteName().trim().toLowerCase()); - } else { - query.setParameter("param", analyte.getAnalyteName()); - } - - List list = query.list(); - - Analyte ana = null; - if (list.size() > 0) { - ana = list.get(0); - } - - return ana; - - } catch (RuntimeException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in Analyte getAnalyteByName()", e); + public AnalyteDAOImpl() { + super(Analyte.class); } - } - - // bugzilla 1482 - @Override - public boolean duplicateAnalyteExists(Analyte analyte) { - try { - - List list = new ArrayList<>(); - - // not case sensitive hemolysis and Hemolysis are considered - // duplicates - - // bugzilla 2432 add check for local abbreviation - String sql = ""; - if (analyte.getLocalAbbreviation() != null) { - sql = - "from Analyte a where (trim(lower(a.analyteName)) = :name and a.id != :id)" - + " or (trim(lower(a.localAbbreviation)) = :abbreviation and a.id != :id)"; - } else { - sql = "from Analyte a where trim(lower(a.analyteName)) = :name and a.id != :id"; - } - - Query query = entityManager.unwrap(Session.class).createQuery(sql, Analyte.class); - query.setParameter("name", analyte.getAnalyteName().toLowerCase().trim()); - // bugzilla 2432 - if (analyte.getLocalAbbreviation() != null) { - query.setParameter("abbreviation", analyte.getLocalAbbreviation().toLowerCase().trim()); - } - - String analyteId = !StringUtil.isNullorNill(analyte.getId()) ? analyte.getId() : "0"; - - query.setParameter("id", Integer.parseInt(analyteId)); - - list = query.list(); - - return list.size() > 0; - } catch (RuntimeException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in duplicateAnalyteExists()", e); + + @Override + public void delete(Analyte analyte) { + LogEvent.logWarn(this.getClass().getSimpleName(), "delete", "delete analyte is not implemented"); + } + + // bugzilla 1367 added ignoreCase + @Override + @Transactional(readOnly = true) + public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) throws LIMSRuntimeException { + try { + + String sql = null; + if (ignoreCase) { + sql = "from Analyte a where trim(lower(a.analyteName)) = :param and a.isActive='Y'"; + + } else { + sql = "from Analyte a where a.analyteName = :param and a.isActive='Y'"; + } + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analyte.class); + + if (ignoreCase) { + query.setParameter("param", analyte.getAnalyteName().trim().toLowerCase()); + } else { + query.setParameter("param", analyte.getAnalyteName()); + } + + List list = query.list(); + + Analyte ana = null; + if (list.size() > 0) { + ana = list.get(0); + } + + return ana; + + } catch (RuntimeException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in Analyte getAnalyteByName()", e); + } + } + + // bugzilla 1482 + @Override + public boolean duplicateAnalyteExists(Analyte analyte) { + try { + + List list = new ArrayList<>(); + + // not case sensitive hemolysis and Hemolysis are considered + // duplicates + + // bugzilla 2432 add check for local abbreviation + String sql = ""; + if (analyte.getLocalAbbreviation() != null) { + sql = "from Analyte a where (trim(lower(a.analyteName)) = :name and a.id != :id)" + + " or (trim(lower(a.localAbbreviation)) = :abbreviation and a.id != :id)"; + } else { + sql = "from Analyte a where trim(lower(a.analyteName)) = :name and a.id != :id"; + } + + Query query = entityManager.unwrap(Session.class).createQuery(sql, Analyte.class); + query.setParameter("name", analyte.getAnalyteName().toLowerCase().trim()); + // bugzilla 2432 + if (analyte.getLocalAbbreviation() != null) { + query.setParameter("abbreviation", analyte.getLocalAbbreviation().toLowerCase().trim()); + } + + String analyteId = !StringUtil.isNullorNill(analyte.getId()) ? analyte.getId() : "0"; + + query.setParameter("id", Integer.parseInt(analyteId)); + + list = query.list(); + + return list.size() > 0; + } catch (RuntimeException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in duplicateAnalyteExists()", e); + } } - } } diff --git a/src/main/java/org/openelisglobal/analyte/service/AnalyteService.java b/src/main/java/org/openelisglobal/analyte/service/AnalyteService.java index 9a1385e881..6b28377efa 100644 --- a/src/main/java/org/openelisglobal/analyte/service/AnalyteService.java +++ b/src/main/java/org/openelisglobal/analyte/service/AnalyteService.java @@ -5,5 +5,5 @@ public interface AnalyteService extends BaseObjectService { - Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase); + Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase); } diff --git a/src/main/java/org/openelisglobal/analyte/service/AnalyteServiceImpl.java b/src/main/java/org/openelisglobal/analyte/service/AnalyteServiceImpl.java index d2bff0cce5..0f7531627a 100644 --- a/src/main/java/org/openelisglobal/analyte/service/AnalyteServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyte/service/AnalyteServiceImpl.java @@ -10,61 +10,58 @@ import org.springframework.transaction.annotation.Transactional; @Service -public class AnalyteServiceImpl extends AuditableBaseObjectServiceImpl - implements AnalyteService { - @Autowired protected AnalyteDAO baseObjectDAO; +public class AnalyteServiceImpl extends AuditableBaseObjectServiceImpl implements AnalyteService { + @Autowired + protected AnalyteDAO baseObjectDAO; - AnalyteServiceImpl() { - super(Analyte.class); - } + AnalyteServiceImpl() { + super(Analyte.class); + } - @Override - protected AnalyteDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected AnalyteDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - @Transactional(readOnly = true) - public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) { - return getBaseObjectDAO().getAnalyteByName(analyte, ignoreCase); - } + @Override + @Transactional(readOnly = true) + public Analyte getAnalyteByName(Analyte analyte, boolean ignoreCase) { + return getBaseObjectDAO().getAnalyteByName(analyte, ignoreCase); + } - @Override - public String insert(Analyte analyte) { - if (duplicateAnalyteExists(analyte)) { - throw new LIMSDuplicateRecordException( - "Duplicate record exists for " + analyte.getAnalyteName()); + @Override + public String insert(Analyte analyte) { + if (duplicateAnalyteExists(analyte)) { + throw new LIMSDuplicateRecordException("Duplicate record exists for " + analyte.getAnalyteName()); + } + return super.insert(analyte); } - return super.insert(analyte); - } - @Override - public Analyte save(Analyte analyte) { - if (duplicateAnalyteExists(analyte)) { - throw new LIMSDuplicateRecordException( - "Duplicate record exists for " + analyte.getAnalyteName()); + @Override + public Analyte save(Analyte analyte) { + if (duplicateAnalyteExists(analyte)) { + throw new LIMSDuplicateRecordException("Duplicate record exists for " + analyte.getAnalyteName()); + } + return super.save(analyte); } - return super.save(analyte); - } - @Override - public Analyte update(Analyte analyte) { - if (duplicateAnalyteExists(analyte)) { - throw new LIMSDuplicateRecordException( - "Duplicate record exists for " + analyte.getAnalyteName()); + @Override + public Analyte update(Analyte analyte) { + if (duplicateAnalyteExists(analyte)) { + throw new LIMSDuplicateRecordException("Duplicate record exists for " + analyte.getAnalyteName()); + } + return super.update(analyte); } - return super.update(analyte); - } - private boolean duplicateAnalyteExists(Analyte analyte) { - return baseObjectDAO.duplicateAnalyteExists(analyte); - } + private boolean duplicateAnalyteExists(Analyte analyte) { + return baseObjectDAO.duplicateAnalyteExists(analyte); + } - @Override - public void delete(Analyte analyte) { - Analyte oldData = get(analyte.getId()); - oldData.setIsActive(IActionConstants.NO); - oldData.setSysUserId(analyte.getSysUserId()); - updateDelete(oldData); - } + @Override + public void delete(Analyte analyte) { + Analyte oldData = get(analyte.getId()); + oldData.setIsActive(IActionConstants.NO); + oldData.setSysUserId(analyte.getSysUserId()); + updateDelete(oldData); + } } diff --git a/src/main/java/org/openelisglobal/analyte/valueholder/Analyte.java b/src/main/java/org/openelisglobal/analyte/valueholder/Analyte.java index 5998eea303..fe006ae546 100644 --- a/src/main/java/org/openelisglobal/analyte/valueholder/Analyte.java +++ b/src/main/java/org/openelisglobal/analyte/valueholder/Analyte.java @@ -19,92 +19,92 @@ public class Analyte extends EnumValueItemImpl { - private String id; + private String id; - // defined in EnumValueItemImpl - // private String isActive; + // defined in EnumValueItemImpl + // private String isActive; - private String externalId; + private String externalId; - private ValueHolderInterface analyte; + private ValueHolderInterface analyte; - private String analyteName; + private String analyteName; - private String selectedAnalyteId; + private String selectedAnalyteId; - // bugzilla 2432 - private String localAbbreviation; + // bugzilla 2432 + private String localAbbreviation; - public Analyte() { - super(); - this.analyte = new ValueHolder(); - } + public Analyte() { + super(); + this.analyte = new ValueHolder(); + } - public String getId() { - return this.id; - } + public String getId() { + return this.id; + } - public String getIsActive() { - return this.isActive; - } + public String getIsActive() { + return this.isActive; + } - public Analyte getAnalyte() { - return (Analyte) this.analyte.getValue(); - } + public Analyte getAnalyte() { + return (Analyte) this.analyte.getValue(); + } - protected ValueHolderInterface getAnalyteHolder() { - return this.analyte; - } + protected ValueHolderInterface getAnalyteHolder() { + return this.analyte; + } - public String getAnalyteName() { - return this.analyteName; - } + public String getAnalyteName() { + return this.analyteName; + } - public void setId(String id) { - this.id = id; - // bugzilla 1625 - this.key = id; - } + public void setId(String id) { + this.id = id; + // bugzilla 1625 + this.key = id; + } - public void setIsActive(String isActive) { - this.isActive = isActive; - } + public void setIsActive(String isActive) { + this.isActive = isActive; + } - public void setAnalyte(Analyte analyte) { - this.analyte.setValue(analyte); - } + public void setAnalyte(Analyte analyte) { + this.analyte.setValue(analyte); + } - protected void setAnalyteHolder(ValueHolderInterface analyte) { - this.analyte = analyte; - } + protected void setAnalyteHolder(ValueHolderInterface analyte) { + this.analyte = analyte; + } - public void setAnalyteName(String analyteName) { - this.analyteName = analyteName; - // bugzilla 1625 - this.name = analyteName; - } + public void setAnalyteName(String analyteName) { + this.analyteName = analyteName; + // bugzilla 1625 + this.name = analyteName; + } - public void setSelectedAnalyteId(String selectedAnalyteId) { - this.selectedAnalyteId = selectedAnalyteId; - } + public void setSelectedAnalyteId(String selectedAnalyteId) { + this.selectedAnalyteId = selectedAnalyteId; + } - public String getSelectedAnalyteId() { - return this.selectedAnalyteId; - } + public String getSelectedAnalyteId() { + return this.selectedAnalyteId; + } - public String getExternalId() { - return externalId; - } + public String getExternalId() { + return externalId; + } - public void setExternalId(String externalId) { - this.externalId = externalId; - } + public void setExternalId(String externalId) { + this.externalId = externalId; + } - public String getLocalAbbreviation() { - return localAbbreviation; - } + public String getLocalAbbreviation() { + return localAbbreviation; + } - public void setLocalAbbreviation(String localAbbreviation) { - this.localAbbreviation = localAbbreviation; - } + public void setLocalAbbreviation(String localAbbreviation) { + this.localAbbreviation = localAbbreviation; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/controller/AnalyzerExperimentController.java b/src/main/java/org/openelisglobal/analyzer/controller/AnalyzerExperimentController.java index 21f69d2f37..a708fcc46a 100644 --- a/src/main/java/org/openelisglobal/analyzer/controller/AnalyzerExperimentController.java +++ b/src/main/java/org/openelisglobal/analyzer/controller/AnalyzerExperimentController.java @@ -39,147 +39,138 @@ @Controller public class AnalyzerExperimentController extends BaseController { - private static final String[] ALLOWED_FIELDS = - new String[] { - "id", "filename", "wellValues", "analyzerId", "previousRun", - }; + private static final String[] ALLOWED_FIELDS = new String[] { "id", "filename", "wellValues", "analyzerId", + "previousRun", }; - @Autowired private AnalyzerExperimentService analyzerExperimentService; - @Autowired private AnalyzerService analyzerService; - @Autowired private AnalyzerTestMappingService analyzerMappingService; - @Autowired private TestService testService; + @Autowired + private AnalyzerExperimentService analyzerExperimentService; + @Autowired + private AnalyzerService analyzerService; + @Autowired + private AnalyzerTestMappingService analyzerMappingService; + @Autowired + private TestService testService; - @ModelAttribute("form") - public AnalyzerSetupForm initForm() { - return new AnalyzerSetupForm(); - } - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setAllowedFields(ALLOWED_FIELDS); - } - - @GetMapping("/AnalyzerSetup") - public ModelAndView displayAnalyzerSetup() { - AnalyzerSetupForm form = new AnalyzerSetupForm(); - PatientSearch patientSearch = new PatientSearch(); - patientSearch.setLoadFromServerWithPatient(true); - patientSearch.setSelectedPatientActionButtonText( - MessageUtil.getMessage("label.patient.search.select.test")); - form.setPatientSearch(patientSearch); - List analyzers = analyzerService.getAllMatching("hasSetupPage", true); - List analyzerLabels = new ArrayList<>(); - Map> analyzersTests = new HashMap<>(); - Map analyzersWellInfo = new HashMap<>(); - for (Analyzer analyzer : analyzers) { - analyzerLabels.add( - new LabelValuePair(analyzer.getDescription(), analyzer.getId().toString())); - analyzersWellInfo.put(analyzer.getId(), new WellInfo(12, 8)); - analyzersTests.put( - analyzer.getId(), - analyzerMappingService.getAllForAnalyzer(analyzer.getId()).stream() - .map( - e -> - new LabelValuePair( - testService.get(e.getTestId()).getLocalizedTestName().getLocalizedValue(), - testService.get(e.getTestId()).getLoinc())) - .collect(Collectors.toList())); - // analyzerTests.put(analyzer.getId(), - // analyzerMappingService.getAllForAnalyzer(analyzer.getId()).stream() - // .map(e -> new LabelValuePair(e.getAnalyzerTestName(), - // e.getTestId())) - // .collect(Collectors.toList())); + @ModelAttribute("form") + public AnalyzerSetupForm initForm() { + return new AnalyzerSetupForm(); + } + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); } - form.setAnalyzers(analyzerLabels); - form.setAnalyzersTests(analyzersTests); - form.setAnalyzersWellInfo(analyzersWellInfo); - // form.setTests(analyzerService.getAllMatching("hasSetupPage", true).stream().map(e -> - // e.)) - form.setPreviousRuns( - analyzerExperimentService.getAllOrdered("lastupdated", true).stream() - .map(e -> new LabelValuePair(e.getName(), e.getId().toString())) - .collect(Collectors.toList())); - return findForward(FWD_SUCCESS, form); - } - @GetMapping(path = "/AnalyzerSetup/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getSetup(@PathVariable Integer id) throws IOException { - Map wellValues = analyzerExperimentService.getWellValuesForId(id); - return ResponseEntity.ok(wellValues); - } + @GetMapping("/AnalyzerSetup") + public ModelAndView displayAnalyzerSetup() { + AnalyzerSetupForm form = new AnalyzerSetupForm(); + PatientSearch patientSearch = new PatientSearch(); + patientSearch.setLoadFromServerWithPatient(true); + patientSearch.setSelectedPatientActionButtonText(MessageUtil.getMessage("label.patient.search.select.test")); + form.setPatientSearch(patientSearch); + List analyzers = analyzerService.getAllMatching("hasSetupPage", true); + List analyzerLabels = new ArrayList<>(); + Map> analyzersTests = new HashMap<>(); + Map analyzersWellInfo = new HashMap<>(); + for (Analyzer analyzer : analyzers) { + analyzerLabels.add(new LabelValuePair(analyzer.getDescription(), analyzer.getId().toString())); + analyzersWellInfo.put(analyzer.getId(), new WellInfo(12, 8)); + analyzersTests.put(analyzer.getId(), + analyzerMappingService.getAllForAnalyzer(analyzer.getId()).stream() + .map(e -> new LabelValuePair( + testService.get(e.getTestId()).getLocalizedTestName().getLocalizedValue(), + testService.get(e.getTestId()).getLoinc())) + .collect(Collectors.toList())); + // analyzerTests.put(analyzer.getId(), + // analyzerMappingService.getAllForAnalyzer(analyzer.getId()).stream() + // .map(e -> new LabelValuePair(e.getAnalyzerTestName(), + // e.getTestId())) + // .collect(Collectors.toList())); - @PostMapping(path = "/AnalyzerSetupAPI", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity saveSetupFile( - @Valid AnalyzerSetupForm form, BindingResult result, RedirectAttributes redirectAttributes) { - if (result.hasErrors()) { - saveErrors(result); - return ResponseEntity.badRequest().build(); + } + form.setAnalyzers(analyzerLabels); + form.setAnalyzersTests(analyzersTests); + form.setAnalyzersWellInfo(analyzersWellInfo); + // form.setTests(analyzerService.getAllMatching("hasSetupPage", + // true).stream().map(e -> + // e.)) + form.setPreviousRuns(analyzerExperimentService.getAllOrdered("lastupdated", true).stream() + .map(e -> new LabelValuePair(e.getName(), e.getId().toString())).collect(Collectors.toList())); + return findForward(FWD_SUCCESS, form); } - try { - Integer id = - analyzerExperimentService.saveMapAsCSVFile(form.getFilename(), form.getWellValues()); - redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); - return ResponseEntity.ok(id); - } catch (LIMSException e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + + @GetMapping(path = "/AnalyzerSetup/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> getSetup(@PathVariable Integer id) throws IOException { + Map wellValues = analyzerExperimentService.getWellValuesForId(id); + return ResponseEntity.ok(wellValues); } - } - @GetMapping(path = "/AnalyzerSetupFile/{id}", produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity getSetupFile( - @PathVariable Integer id, - @RequestParam("fileName") @Pattern(regexp = "^[\\w]+$") String fileName, - BindingResult result) { - if (result.hasErrors()) { - saveErrors(result); - return ResponseEntity.badRequest().build(); + @PostMapping(path = "/AnalyzerSetupAPI", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity saveSetupFile(@Valid AnalyzerSetupForm form, BindingResult result, + RedirectAttributes redirectAttributes) { + if (result.hasErrors()) { + saveErrors(result); + return ResponseEntity.badRequest().build(); + } + try { + Integer id = analyzerExperimentService.saveMapAsCSVFile(form.getFilename(), form.getWellValues()); + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + return ResponseEntity.ok(id); + } catch (LIMSException e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } } - byte[] file = analyzerExperimentService.get(id).getFile(); - return ResponseEntity.ok() - .header("Content-Disposition", "attachment; filename=" + fileName + ".csv") - .contentLength(file.length) - .body(file); - } - @PostMapping("/AnalyzerSetup") - public ModelAndView showSaveSetupFile( - @Valid AnalyzerSetupForm form, BindingResult result, RedirectAttributes redirectAttributes) { - if (result.hasErrors()) { - saveErrors(result); - return findForward(FWD_FAIL_INSERT, form); + @GetMapping(path = "/AnalyzerSetupFile/{id}", produces = MediaType.TEXT_PLAIN_VALUE) + public ResponseEntity getSetupFile(@PathVariable Integer id, + @RequestParam("fileName") @Pattern(regexp = "^[\\w]+$") String fileName, BindingResult result) { + if (result.hasErrors()) { + saveErrors(result); + return ResponseEntity.badRequest().build(); + } + byte[] file = analyzerExperimentService.get(id).getFile(); + return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + fileName + ".csv") + .contentLength(file.length).body(file); } - try { - analyzerExperimentService.saveMapAsCSVFile(form.getFilename(), form.getWellValues()); - } catch (LIMSException e) { - return findForward(FWD_FAIL_INSERT, form); + + @PostMapping("/AnalyzerSetup") + public ModelAndView showSaveSetupFile(@Valid AnalyzerSetupForm form, BindingResult result, + RedirectAttributes redirectAttributes) { + if (result.hasErrors()) { + saveErrors(result); + return findForward(FWD_FAIL_INSERT, form); + } + try { + analyzerExperimentService.saveMapAsCSVFile(form.getFilename(), form.getWellValues()); + } catch (LIMSException e) { + return findForward(FWD_FAIL_INSERT, form); + } + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + return findForward(FWD_SUCCESS_INSERT, form); } - redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); - return findForward(FWD_SUCCESS_INSERT, form); - } - @Override - protected String findLocalForward(String forward) { - switch (forward) { - case FWD_SUCCESS: - return "quantStudioSetupDefinition"; - case FWD_SUCCESS_INSERT: - return "redirect:/AnalyzerSetup.dp"; - case FWD_FAIL_INSERT: - return "quantStudioSetupDefinition"; + @Override + protected String findLocalForward(String forward) { + switch (forward) { + case FWD_SUCCESS: + return "quantStudioSetupDefinition"; + case FWD_SUCCESS_INSERT: + return "redirect:/AnalyzerSetup.dp"; + case FWD_FAIL_INSERT: + return "quantStudioSetupDefinition"; + } + return null; } - return null; - } - @Override - protected String getPageTitleKey() { - // TODO Auto-generated method stub - return null; - } + @Override + protected String getPageTitleKey() { + // TODO Auto-generated method stub + return null; + } - @Override - protected String getPageSubtitleKey() { - // TODO Auto-generated method stub - return null; - } + @Override + protected String getPageSubtitleKey() { + // TODO Auto-generated method stub + return null; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/controller/ListPluginsController.java b/src/main/java/org/openelisglobal/analyzer/controller/ListPluginsController.java index 58484a30a3..d6ac32dfea 100644 --- a/src/main/java/org/openelisglobal/analyzer/controller/ListPluginsController.java +++ b/src/main/java/org/openelisglobal/analyzer/controller/ListPluginsController.java @@ -16,44 +16,44 @@ @Controller public class ListPluginsController extends BaseController { - // form isn't submitted back - private static final String[] ALLOWED_FIELDS = new String[] {}; + // form isn't submitted back + private static final String[] ALLOWED_FIELDS = new String[] {}; - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setAllowedFields(ALLOWED_FIELDS); - } + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } - @RequestMapping(value = "/ListPlugins", method = RequestMethod.GET) - public ModelAndView showListPlugins(HttpServletRequest request) { - ListPluginForm form = new ListPluginForm(); + @RequestMapping(value = "/ListPlugins", method = RequestMethod.GET) + public ModelAndView showListPlugins(HttpServletRequest request) { + ListPluginForm form = new ListPluginForm(); - List pluginNames = PluginLoader.getCurrentPlugins(); + List pluginNames = PluginLoader.getCurrentPlugins(); - if (pluginNames.isEmpty()) { - pluginNames.add(MessageUtil.getContextualMessage("plugin.no.plugins")); - } - form.setPluginList(pluginNames); + if (pluginNames.isEmpty()) { + pluginNames.add(MessageUtil.getContextualMessage("plugin.no.plugins")); + } + form.setPluginList(pluginNames); - return findForward(FWD_SUCCESS, form); - } + return findForward(FWD_SUCCESS, form); + } - @Override - protected String findLocalForward(String forward) { - if (FWD_SUCCESS.equals(forward)) { - return "ListPluginsPageDefinition"; - } else { - return "PageNotFound"; + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "ListPluginsPageDefinition"; + } else { + return "PageNotFound"; + } } - } - @Override - protected String getPageTitleKey() { - return "plugin.installed.plugins"; - } + @Override + protected String getPageTitleKey() { + return "plugin.installed.plugins"; + } - @Override - protected String getPageSubtitleKey() { - return "plugin.installed.plugins"; - } + @Override + protected String getPageSubtitleKey() { + return "plugin.installed.plugins"; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/controller/rest/ListPluginsRestController.java b/src/main/java/org/openelisglobal/analyzer/controller/rest/ListPluginsRestController.java new file mode 100644 index 0000000000..8ce67db80e --- /dev/null +++ b/src/main/java/org/openelisglobal/analyzer/controller/rest/ListPluginsRestController.java @@ -0,0 +1,60 @@ +package org.openelisglobal.analyzer.controller.rest; + +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import org.openelisglobal.analyzer.form.ListPluginForm; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.internationalization.MessageUtil; +import org.openelisglobal.plugin.PluginLoader; +import org.springframework.http.MediaType; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/rest") +public class ListPluginsRestController extends BaseController { + + // form isn't submitted back + private static final String[] ALLOWED_FIELDS = new String[] {}; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/ListPlugins", produces = MediaType.APPLICATION_JSON_VALUE) + public ListPluginForm showListPlugins(HttpServletRequest request) { + ListPluginForm form = new ListPluginForm(); + + List pluginNames = PluginLoader.getCurrentPlugins(); + + if (pluginNames.isEmpty()) { + pluginNames.add(MessageUtil.getContextualMessage("plugin.no.plugins")); + } + form.setPluginList(pluginNames); + + return form; + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "ListPluginsPageDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return "plugin.installed.plugins"; + } + + @Override + protected String getPageSubtitleKey() { + return "plugin.installed.plugins"; + } +} diff --git a/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerDAO.java b/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerDAO.java index 1a2f94202c..8a23fff000 100644 --- a/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerDAO.java +++ b/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerDAO.java @@ -18,19 +18,20 @@ public interface AnalyzerDAO extends BaseDAO { - // public boolean insertData(Analyzer analyzer) throws LIMSRuntimeException; + // public boolean insertData(Analyzer analyzer) throws LIMSRuntimeException; - // public void deleteData(List results) throws LIMSRuntimeException; + // public void deleteData(List results) throws LIMSRuntimeException; - // public List getAllAnalyzers() throws LIMSRuntimeException; + // public List getAllAnalyzers() throws LIMSRuntimeException; - // public Analyzer readAnalyzer(String idString) throws LIMSRuntimeException; + // public Analyzer readAnalyzer(String idString) throws LIMSRuntimeException; - // public void getData(Analyzer analyzer) throws LIMSRuntimeException; + // public void getData(Analyzer analyzer) throws LIMSRuntimeException; - // public void updateData(Analyzer analyzer) throws LIMSRuntimeException; + // public void updateData(Analyzer analyzer) throws LIMSRuntimeException; - // public Analyzer getAnalyzerById(Analyzer analyzer) throws LIMSRuntimeException; + // public Analyzer getAnalyzerById(Analyzer analyzer) throws + // LIMSRuntimeException; - // public Analyzer getAnalyzerByName(String name) throws LIMSRuntimeException; + // public Analyzer getAnalyzerByName(String name) throws LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerExperimentDAO.java b/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerExperimentDAO.java index 53b83b881a..9c5f56e2f4 100644 --- a/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerExperimentDAO.java +++ b/src/main/java/org/openelisglobal/analyzer/dao/AnalyzerExperimentDAO.java @@ -3,4 +3,5 @@ import org.openelisglobal.analyzer.valueholder.AnalyzerExperiment; import org.openelisglobal.common.dao.BaseDAO; -public interface AnalyzerExperimentDAO extends BaseDAO {} +public interface AnalyzerExperimentDAO extends BaseDAO { +} diff --git a/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerDAOImpl.java b/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerDAOImpl.java index 3663145b90..b3daaa24ee 100644 --- a/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerDAOImpl.java +++ b/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerDAOImpl.java @@ -23,7 +23,7 @@ @Transactional public class AnalyzerDAOImpl extends BaseDAOImpl implements AnalyzerDAO { - public AnalyzerDAOImpl() { - super(Analyzer.class); - } + public AnalyzerDAOImpl() { + super(Analyzer.class); + } } diff --git a/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerExperimentDAOImpl.java b/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerExperimentDAOImpl.java index ef84af6ee6..aee4afe552 100644 --- a/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerExperimentDAOImpl.java +++ b/src/main/java/org/openelisglobal/analyzer/daoimpl/AnalyzerExperimentDAOImpl.java @@ -7,9 +7,9 @@ @Component public class AnalyzerExperimentDAOImpl extends BaseDAOImpl - implements AnalyzerExperimentDAO { + implements AnalyzerExperimentDAO { - public AnalyzerExperimentDAOImpl() { - super(AnalyzerExperiment.class); - } + public AnalyzerExperimentDAOImpl() { + super(AnalyzerExperiment.class); + } } diff --git a/src/main/java/org/openelisglobal/analyzer/form/AnalyzerSetupForm.java b/src/main/java/org/openelisglobal/analyzer/form/AnalyzerSetupForm.java index 13ec201a68..900a7372a9 100644 --- a/src/main/java/org/openelisglobal/analyzer/form/AnalyzerSetupForm.java +++ b/src/main/java/org/openelisglobal/analyzer/form/AnalyzerSetupForm.java @@ -9,93 +9,93 @@ public class AnalyzerSetupForm extends BaseForm { - private PatientSearch patientSearch; + private PatientSearch patientSearch; - private String filename; + private String filename; - private Map wellValues; + private Map wellValues; - private List previousRuns; + private List previousRuns; - private List analyzers; + private List analyzers; - private Map> analyzersTests; + private Map> analyzersTests; - private Map analyzersWellInfo; + private Map analyzersWellInfo; - private String analyzerId; + private String analyzerId; - private Integer previousRun; + private Integer previousRun; - public PatientSearch getPatientSearch() { - return patientSearch; - } + public PatientSearch getPatientSearch() { + return patientSearch; + } - public void setPatientSearch(PatientSearch patientSearch) { - this.patientSearch = patientSearch; - } + public void setPatientSearch(PatientSearch patientSearch) { + this.patientSearch = patientSearch; + } - public String getFilename() { - return filename; - } + public String getFilename() { + return filename; + } - public void setFilename(String filename) { - this.filename = filename; - } + public void setFilename(String filename) { + this.filename = filename; + } - public Map getWellValues() { - return wellValues; - } + public Map getWellValues() { + return wellValues; + } - public void setWellValues(Map wellValues) { - this.wellValues = wellValues; - } + public void setWellValues(Map wellValues) { + this.wellValues = wellValues; + } - public List getPreviousRuns() { - return previousRuns; - } + public List getPreviousRuns() { + return previousRuns; + } - public void setPreviousRuns(List previousRuns) { - this.previousRuns = previousRuns; - } + public void setPreviousRuns(List previousRuns) { + this.previousRuns = previousRuns; + } - public Integer getPreviousRun() { - return previousRun; - } + public Integer getPreviousRun() { + return previousRun; + } - public void setPreviousRun(Integer previousRun) { - this.previousRun = previousRun; - } + public void setPreviousRun(Integer previousRun) { + this.previousRun = previousRun; + } - public List getAnalyzers() { - return analyzers; - } + public List getAnalyzers() { + return analyzers; + } - public void setAnalyzers(List analyzers) { - this.analyzers = analyzers; - } + public void setAnalyzers(List analyzers) { + this.analyzers = analyzers; + } - public String getAnalyzerId() { - return analyzerId; - } + public String getAnalyzerId() { + return analyzerId; + } - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } - public Map> getAnalyzersTests() { - return analyzersTests; - } + public Map> getAnalyzersTests() { + return analyzersTests; + } - public void setAnalyzersTests(Map> analyzersTests) { - this.analyzersTests = analyzersTests; - } + public void setAnalyzersTests(Map> analyzersTests) { + this.analyzersTests = analyzersTests; + } - public Map getAnalyzersWellInfo() { - return analyzersWellInfo; - } + public Map getAnalyzersWellInfo() { + return analyzersWellInfo; + } - public void setAnalyzersWellInfo(Map analyzersWellInfo) { - this.analyzersWellInfo = analyzersWellInfo; - } + public void setAnalyzersWellInfo(Map analyzersWellInfo) { + this.analyzersWellInfo = analyzersWellInfo; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/form/ListPluginForm.java b/src/main/java/org/openelisglobal/analyzer/form/ListPluginForm.java index 5e94f17b51..fa9308f263 100644 --- a/src/main/java/org/openelisglobal/analyzer/form/ListPluginForm.java +++ b/src/main/java/org/openelisglobal/analyzer/form/ListPluginForm.java @@ -6,17 +6,17 @@ public class ListPluginForm extends BaseForm { - private List<@SafeHtml String> pluginList; + private List<@SafeHtml String> pluginList; - public ListPluginForm() { - setFormName("listPluginForm"); - } + public ListPluginForm() { + setFormName("listPluginForm"); + } - public List getPluginList() { - return pluginList; - } + public List getPluginList() { + return pluginList; + } - public void setPluginList(List pluginList) { - this.pluginList = pluginList; - } + public void setPluginList(List pluginList) { + this.pluginList = pluginList; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentService.java b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentService.java index ae60eacf96..edd48cdeae 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentService.java +++ b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentService.java @@ -8,7 +8,7 @@ public interface AnalyzerExperimentService extends BaseObjectService { - Integer saveMapAsCSVFile(String filename, Map wellValues) throws LIMSException; + Integer saveMapAsCSVFile(String filename, Map wellValues) throws LIMSException; - Map getWellValuesForId(Integer id) throws IOException; + Map getWellValuesForId(Integer id) throws IOException; } diff --git a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentServiceImpl.java b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentServiceImpl.java index 1bf5bea3a1..f41c7ba9af 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerExperimentServiceImpl.java @@ -26,97 +26,94 @@ import org.springframework.stereotype.Service; @Service -public class AnalyzerExperimentServiceImpl - extends AuditableBaseObjectServiceImpl - implements AnalyzerExperimentService { +public class AnalyzerExperimentServiceImpl extends AuditableBaseObjectServiceImpl + implements AnalyzerExperimentService { - @Autowired private AnalyzerExperimentDAO baseDAO; + @Autowired + private AnalyzerExperimentDAO baseDAO; - public AnalyzerExperimentServiceImpl() { - super(AnalyzerExperiment.class); - } + public AnalyzerExperimentServiceImpl() { + super(AnalyzerExperiment.class); + } - @Override - protected BaseDAO getBaseObjectDAO() { - return baseDAO; - } + @Override + protected BaseDAO getBaseObjectDAO() { + return baseDAO; + } - @Override - public Map getWellValuesForId(Integer id) throws IOException { - Map wellValues = new HashMap<>(); - AnalyzerExperiment analyzerExperiment = get(id); - BufferedReader reader = - new BufferedReader( - new InputStreamReader(new ByteArrayInputStream(analyzerExperiment.getFile()))); - String[] columns = reader.readLine().split(","); - while (reader.ready()) { - String[] pair = reader.readLine().split(","); - wellValues.put(pair[0], pair.length == 2 ? pair[1] : ""); + @Override + public Map getWellValuesForId(Integer id) throws IOException { + Map wellValues = new HashMap<>(); + AnalyzerExperiment analyzerExperiment = get(id); + BufferedReader reader = new BufferedReader( + new InputStreamReader(new ByteArrayInputStream(analyzerExperiment.getFile()))); + String[] columns = reader.readLine().split(","); + while (reader.ready()) { + String[] pair = reader.readLine().split(","); + wellValues.put(pair[0], pair.length == 2 ? pair[1] : ""); + } + return wellValues; } - return wellValues; - } - @Override - public Integer saveMapAsCSVFile(String filename, Map wellValues) - throws LIMSException { - AnalyzerExperiment analyzerExperiment = new AnalyzerExperiment(); - analyzerExperiment.setName(filename); - analyzerExperiment.setFile(generateCSV(wellValues)); - return baseDAO.insert(analyzerExperiment); - } + @Override + public Integer saveMapAsCSVFile(String filename, Map wellValues) throws LIMSException { + AnalyzerExperiment analyzerExperiment = new AnalyzerExperiment(); + analyzerExperiment.setName(filename); + analyzerExperiment.setFile(generateCSV(wellValues)); + return baseDAO.insert(analyzerExperiment); + } - private byte[] generateCSV(Map wellValues) throws LIMSException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (Writer writer = new PrintWriter(outputStream)) { - writer.append("well").append(',').append("Sample Name").append('\n'); - List> entries = - wellValues.entrySet().stream().collect(Collectors.toList()); - Collections.sort(entries, new WellValueComparator()); - for (Entry entry : entries) { - writer.append(entry.getKey()).append(',').append(entry.getValue()).append('\n'); - } - } catch (IOException e) { - LogEvent.logError(e); - throw new LIMSException("could not generate the csv"); + private byte[] generateCSV(Map wellValues) throws LIMSException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (Writer writer = new PrintWriter(outputStream)) { + writer.append("well").append(',').append("Sample Name").append('\n'); + List> entries = wellValues.entrySet().stream().collect(Collectors.toList()); + Collections.sort(entries, new WellValueComparator()); + for (Entry entry : entries) { + writer.append(entry.getKey()).append(',').append(entry.getValue()).append('\n'); + } + } catch (IOException e) { + LogEvent.logError(e); + throw new LIMSException("could not generate the csv"); + } + return outputStream.toByteArray(); } - return outputStream.toByteArray(); - } - public class WellValueComparator implements Comparator> { + public class WellValueComparator implements Comparator> { - @Override - public int compare(Entry firstEntry, Entry secondEntry) { - Pattern pattern = Pattern.compile("([A-Z]+)(\\d+)"); - Matcher matcher = pattern.matcher(firstEntry.getKey()); - matcher.find(); - String firstAlpha = matcher.group(1); - String firstNum = matcher.group(2); + @Override + public int compare(Entry firstEntry, Entry secondEntry) { + Pattern pattern = Pattern.compile("([A-Z]+)(\\d+)"); + Matcher matcher = pattern.matcher(firstEntry.getKey()); + matcher.find(); + String firstAlpha = matcher.group(1); + String firstNum = matcher.group(2); - matcher = pattern.matcher(secondEntry.getKey()); - matcher.find(); - String secondAlpha = matcher.group(1); - String secondNum = matcher.group(2); + matcher = pattern.matcher(secondEntry.getKey()); + matcher.find(); + String secondAlpha = matcher.group(1); + String secondNum = matcher.group(2); - int compareVal = compareLengthAware(firstAlpha, secondAlpha); - if (compareVal == 0) { - compareVal = compareLengthAware(firstNum, secondNum); - } + int compareVal = compareLengthAware(firstAlpha, secondAlpha); + if (compareVal == 0) { + compareVal = compareLengthAware(firstNum, secondNum); + } - return compareVal; - } + return compareVal; + } - private int compareLengthAware(String first, String second) { - if (first.length() > second.length()) { - return 1; - } else if (first.length() < second.length()) { - return -1; - } else if (first.compareTo(second) > 0) { - return 1; - } else if (first.compareTo(second) < 0) { - return -1; - } else { - return 0; - } + private int compareLengthAware(String first, String second) { + if (first.length() > second.length()) { + return 1; + } else if (first.length() < second.length()) { + return -1; + } else if (first.compareTo(second) > 0) { + return 1; + } else if (first.compareTo(second) < 0) { + return -1; + } else { + return 0; + } + } } - } } diff --git a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerService.java b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerService.java index d8cd901525..f721a798ff 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerService.java +++ b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerService.java @@ -6,10 +6,8 @@ import org.openelisglobal.common.service.BaseObjectService; public interface AnalyzerService extends BaseObjectService { - Analyzer getAnalyzerByName(String name); + Analyzer getAnalyzerByName(String name); - void persistData( - Analyzer analyzer, - List testMappings, - List existingMappings); + void persistData(Analyzer analyzer, List testMappings, + List existingMappings); } diff --git a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerServiceImpl.java b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerServiceImpl.java index 24b6438c31..5072a43ca8 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/AnalyzerServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyzer/service/AnalyzerServiceImpl.java @@ -11,61 +11,59 @@ import org.springframework.transaction.annotation.Transactional; @Service -public class AnalyzerServiceImpl extends AuditableBaseObjectServiceImpl - implements AnalyzerService { - @Autowired protected AnalyzerDAO baseObjectDAO; - @Autowired private AnalyzerTestMappingService analyzerMappingService; +public class AnalyzerServiceImpl extends AuditableBaseObjectServiceImpl implements AnalyzerService { + @Autowired + protected AnalyzerDAO baseObjectDAO; + @Autowired + private AnalyzerTestMappingService analyzerMappingService; - AnalyzerServiceImpl() { - super(Analyzer.class); - } - - @Override - protected AnalyzerDAO getBaseObjectDAO() { - return baseObjectDAO; - } + AnalyzerServiceImpl() { + super(Analyzer.class); + } - @Override - @Transactional(readOnly = true) - public Analyzer getAnalyzerByName(String name) { - return getMatch("name", name).orElse(null); - } + @Override + protected AnalyzerDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - @Transactional - public void persistData( - Analyzer analyzer, - List testMappings, - List existingMappings) { - if (analyzer.getId() == null) { - insert(analyzer); - } else { - update(analyzer); + @Override + @Transactional(readOnly = true) + public Analyzer getAnalyzerByName(String name) { + return getMatch("name", name).orElse(null); } - for (AnalyzerTestMapping mapping : testMappings) { - mapping.setAnalyzerId(analyzer.getId()); - if (newMapping(mapping, existingMappings)) { - mapping.setSysUserId("1"); - analyzerMappingService.insert(mapping); - existingMappings.add(mapping); - } else { - mapping.setLastupdated(analyzerMappingService.get(mapping.getId()).getLastupdated()); - mapping.setSysUserId("1"); - // update in case mapping was preserved before test was made - analyzerMappingService.update(mapping); - } + @Override + @Transactional + public void persistData(Analyzer analyzer, List testMappings, + List existingMappings) { + if (analyzer.getId() == null) { + insert(analyzer); + } else { + update(analyzer); + } + + for (AnalyzerTestMapping mapping : testMappings) { + mapping.setAnalyzerId(analyzer.getId()); + if (newMapping(mapping, existingMappings)) { + mapping.setSysUserId("1"); + analyzerMappingService.insert(mapping); + existingMappings.add(mapping); + } else { + mapping.setLastupdated(analyzerMappingService.get(mapping.getId()).getLastupdated()); + mapping.setSysUserId("1"); + // update in case mapping was preserved before test was made + analyzerMappingService.update(mapping); + } + } } - } - private boolean newMapping( - AnalyzerTestMapping mapping, List existingMappings) { - for (AnalyzerTestMapping existingMap : existingMappings) { - if (existingMap.getAnalyzerId().equals(mapping.getAnalyzerId()) - && existingMap.getAnalyzerTestName().equals(mapping.getAnalyzerTestName())) { - return false; - } + private boolean newMapping(AnalyzerTestMapping mapping, List existingMappings) { + for (AnalyzerTestMapping existingMap : existingMappings) { + if (existingMap.getAnalyzerId().equals(mapping.getAnalyzerId()) + && existingMap.getAnalyzerTestName().equals(mapping.getAnalyzerTestName())) { + return false; + } + } + return true; } - return true; - } } diff --git a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzer.java b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzer.java index 366c4a6195..fbe3e95706 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzer.java +++ b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzer.java @@ -7,55 +7,55 @@ public interface BidirectionalAnalyzer { - List getSupportedLISActions(); + List getSupportedLISActions(); - boolean runLISAction(String actionName, Map actionParameters); + boolean runLISAction(String actionName, Map actionParameters); - public class LISAction { - private String actionName; - private Map displayNames; - private boolean automaticAction = false; - private int actionFrequency = 30; - private TimeUnit frequencyTimeUnit = TimeUnit.SECONDS; + public class LISAction { + private String actionName; + private Map displayNames; + private boolean automaticAction = false; + private int actionFrequency = 30; + private TimeUnit frequencyTimeUnit = TimeUnit.SECONDS; - public String getActionName() { - return actionName; - } + public String getActionName() { + return actionName; + } - public void setActionName(String actionName) { - this.actionName = actionName; - } + public void setActionName(String actionName) { + this.actionName = actionName; + } - public boolean isAutomaticAction() { - return automaticAction; - } + public boolean isAutomaticAction() { + return automaticAction; + } - public void setAutomaticAction(boolean automaticAction) { - this.automaticAction = automaticAction; - } + public void setAutomaticAction(boolean automaticAction) { + this.automaticAction = automaticAction; + } - public int getActionFrequency() { - return actionFrequency; - } + public int getActionFrequency() { + return actionFrequency; + } - public void setActionFrequency(int actionFrequency) { - this.actionFrequency = actionFrequency; - } + public void setActionFrequency(int actionFrequency) { + this.actionFrequency = actionFrequency; + } - public TimeUnit getFrequencyTimeUnit() { - return frequencyTimeUnit; - } + public TimeUnit getFrequencyTimeUnit() { + return frequencyTimeUnit; + } - public void setFrequencyTimeUnit(TimeUnit frequencyTimeUnit) { - this.frequencyTimeUnit = frequencyTimeUnit; - } + public void setFrequencyTimeUnit(TimeUnit frequencyTimeUnit) { + this.frequencyTimeUnit = frequencyTimeUnit; + } - public Map getDisplayNames() { - return displayNames; - } + public Map getDisplayNames() { + return displayNames; + } - public void setDisplayNames(Map displayNames) { - this.displayNames = displayNames; + public void setDisplayNames(Map displayNames) { + this.displayNames = displayNames; + } } - } } diff --git a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerService.java b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerService.java index 2b9685d89c..90cd347ea8 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerService.java +++ b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerService.java @@ -1,3 +1,4 @@ package org.openelisglobal.analyzer.service; -public interface BidirectionalAnalyzerService {} +public interface BidirectionalAnalyzerService { +} diff --git a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerServiceImpl.java b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerServiceImpl.java index 0081036408..a6d5104fab 100644 --- a/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyzer/service/BidirectionalAnalyzerServiceImpl.java @@ -1,3 +1,4 @@ package org.openelisglobal.analyzer.service; -public class BidirectionalAnalyzerServiceImpl {} +public class BidirectionalAnalyzerServiceImpl { +} diff --git a/src/main/java/org/openelisglobal/analyzer/valueholder/Analyzer.java b/src/main/java/org/openelisglobal/analyzer/valueholder/Analyzer.java index 2d1184639c..33d7200faf 100644 --- a/src/main/java/org/openelisglobal/analyzer/valueholder/Analyzer.java +++ b/src/main/java/org/openelisglobal/analyzer/valueholder/Analyzer.java @@ -21,89 +21,89 @@ */ public class Analyzer extends BaseObject { - private static final long serialVersionUID = 1L; - - private String id; - private String script_id; - private String name; - private String machineId; - private String type; - private String description; - private String location; - private boolean active; - private boolean hasSetupPage; - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - public String getScript_id() { - return script_id; - } - - public void setScript_id(String script_id) { - this.script_id = script_id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void setMachineId(String machineId) { - this.machineId = machineId; - } - - public String getMachineId() { - return machineId; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - - public boolean getHasSetupPage() { - return hasSetupPage; - } - - public void setHasSetupPage(boolean hasSetupPage) { - this.hasSetupPage = hasSetupPage; - } + private static final long serialVersionUID = 1L; + + private String id; + private String script_id; + private String name; + private String machineId; + private String type; + private String description; + private String location; + private boolean active; + private boolean hasSetupPage; + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + public String getScript_id() { + return script_id; + } + + public void setScript_id(String script_id) { + this.script_id = script_id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public void setMachineId(String machineId) { + this.machineId = machineId; + } + + public String getMachineId() { + return machineId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public boolean getHasSetupPage() { + return hasSetupPage; + } + + public void setHasSetupPage(boolean hasSetupPage) { + this.hasSetupPage = hasSetupPage; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/valueholder/AnalyzerExperiment.java b/src/main/java/org/openelisglobal/analyzer/valueholder/AnalyzerExperiment.java index aae1b7ee29..1443b7c574 100644 --- a/src/main/java/org/openelisglobal/analyzer/valueholder/AnalyzerExperiment.java +++ b/src/main/java/org/openelisglobal/analyzer/valueholder/AnalyzerExperiment.java @@ -16,51 +16,48 @@ @Table(name = "analyzer_experiment") public class AnalyzerExperiment extends BaseObject { - private static final long serialVersionUID = -219455306834962412L; - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "analyzer_experiment_generator") - @SequenceGenerator( - name = "analyzer_experiment_generator", - sequenceName = "analyzer_experiment_seq", - allocationSize = 1) - @Column(name = "id") - private Integer id; - - @Valid - @OneToOne - @JoinColumn(name = "analyzer_id", referencedColumnName = "id") - private Analyzer analyzer; - - @Column(name = "name") - private String name; - - @Column(name = "file") - private byte[] file; - - @Override - public Integer getId() { - return id; - } - - @Override - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte[] getFile() { - return file; - } - - public void setFile(byte[] file) { - this.file = file; - } + private static final long serialVersionUID = -219455306834962412L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "analyzer_experiment_generator") + @SequenceGenerator(name = "analyzer_experiment_generator", sequenceName = "analyzer_experiment_seq", allocationSize = 1) + @Column(name = "id") + private Integer id; + + @Valid + @OneToOne + @JoinColumn(name = "analyzer_id", referencedColumnName = "id") + private Analyzer analyzer; + + @Column(name = "name") + private String name; + + @Column(name = "file") + private byte[] file; + + @Override + public Integer getId() { + return id; + } + + @Override + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public byte[] getFile() { + return file; + } + + public void setFile(byte[] file) { + this.file = file; + } } diff --git a/src/main/java/org/openelisglobal/analyzer/valueholder/WellInfo.java b/src/main/java/org/openelisglobal/analyzer/valueholder/WellInfo.java index d1e2626462..6f392cb3ce 100644 --- a/src/main/java/org/openelisglobal/analyzer/valueholder/WellInfo.java +++ b/src/main/java/org/openelisglobal/analyzer/valueholder/WellInfo.java @@ -2,28 +2,28 @@ public class WellInfo { - private int wellRows; + private int wellRows; - private int wellColumns; + private int wellColumns; - public WellInfo(int wellColumns, int wellRows) { - this.wellColumns = wellColumns; - this.wellRows = wellRows; - } + public WellInfo(int wellColumns, int wellRows) { + this.wellColumns = wellColumns; + this.wellRows = wellRows; + } - public int getWellRows() { - return wellRows; - } + public int getWellRows() { + return wellRows; + } - public void setWellRows(int wellRows) { - this.wellRows = wellRows; - } + public void setWellRows(int wellRows) { + this.wellRows = wellRows; + } - public int getWellColumns() { - return wellColumns; - } + public int getWellColumns() { + return wellColumns; + } - public void setWellColumns(int wellColumns) { - this.wellColumns = wellColumns; - } + public void setWellColumns(int wellColumns) { + this.wellColumns = wellColumns; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/action/AnalyzerImportController.java b/src/main/java/org/openelisglobal/analyzerimport/action/AnalyzerImportController.java index f9b3c6b4c8..18ecb2c019 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/action/AnalyzerImportController.java +++ b/src/main/java/org/openelisglobal/analyzerimport/action/AnalyzerImportController.java @@ -41,172 +41,167 @@ @Controller public class AnalyzerImportController implements IActionConstants { - @Autowired protected LoginUserService loginService; - @Autowired protected SystemUserService systemUserService; - @Autowired private PluginAnalyzerService pluginAnalyzerService; + @Autowired + protected LoginUserService loginService; + @Autowired + protected SystemUserService systemUserService; + @Autowired + private PluginAnalyzerService pluginAnalyzerService; - @PostMapping("/importAnalyzer") - protected void doPost( - @RequestParam("file") MultipartFile file, - HttpServletRequest request, - HttpServletResponse response) - throws ServletException, IOException { + @PostMapping("/importAnalyzer") + protected void doPost(@RequestParam("file") MultipartFile file, HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { - AnalyzerReader reader = null; - boolean fileRead = false; - InputStream stream = file.getInputStream(); + AnalyzerReader reader = null; + boolean fileRead = false; + InputStream stream = file.getInputStream(); - reader = AnalyzerReaderFactory.getReaderFor(file.getOriginalFilename()); + reader = AnalyzerReaderFactory.getReaderFor(file.getOriginalFilename()); - if (reader != null) { - fileRead = reader.readStream(stream); - } - if (fileRead) { - boolean successful = reader.insertAnalyzerData(getSysUserId(request)); - - if (successful) { - response.getWriter().print("success"); - response.setStatus(HttpServletResponse.SC_OK); - return; - } else { if (reader != null) { - response.getWriter().print(reader.getError()); + fileRead = reader.readStream(stream); + } + if (fileRead) { + boolean successful = reader.insertAnalyzerData(getSysUserId(request)); + + if (successful) { + response.getWriter().print("success"); + response.setStatus(HttpServletResponse.SC_OK); + return; + } else { + if (reader != null) { + response.getWriter().print(reader.getError()); + } + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + } else { + if (reader != null) { + response.getWriter().print(reader.getError()); + } + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; } - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - - } else { - if (reader != null) { - response.getWriter().print(reader.getError()); - } - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; } - } - @PostMapping("/analyzer/astm") - public void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + @PostMapping("/analyzer/astm") + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ASTMAnalyzerReader reader = null; - boolean read = false; - InputStream stream = request.getInputStream(); + ASTMAnalyzerReader reader = null; + boolean read = false; + InputStream stream = request.getInputStream(); - reader = (ASTMAnalyzerReader) AnalyzerReaderFactory.getReaderFor("astm"); + reader = (ASTMAnalyzerReader) AnalyzerReaderFactory.getReaderFor("astm"); - if (reader != null) { - read = reader.readStream(stream); - if (read) { - boolean success = reader.processData(getSysUserId(request)); - if (reader.hasResponse()) { - response.getWriter().print(reader.getResponse()); - } - if (success) { - response.setStatus(HttpServletResponse.SC_OK); - return; + if (reader != null) { + read = reader.readStream(stream); + if (read) { + boolean success = reader.processData(getSysUserId(request)); + if (reader.hasResponse()) { + response.getWriter().print(reader.getResponse()); + } + if (success) { + response.setStatus(HttpServletResponse.SC_OK); + return; + } else { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + } else { + response.getWriter().print(reader.getError()); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } } else { - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; } - } else { - response.getWriter().print(reader.getError()); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - } else { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; } - } - - @PostMapping("/analyzer/runAction") - public ResponseEntity runAnalyzerAction( - @RequestParam String analyzerType, @RequestParam String actionName) { - AnalyzerImporterPlugin analyzerPlugin = - pluginAnalyzerService.getPluginByAnalyzerId( - AnalyzerTestNameCache.getInstance() - .getAnalyzerIdForName(getAnalyzerNameFromType(analyzerType))); - if (analyzerPlugin instanceof BidirectionalAnalyzer) { - BidirectionalAnalyzer bidirectionalAnalyzer = (BidirectionalAnalyzer) analyzerPlugin; - boolean success = bidirectionalAnalyzer.runLISAction(actionName, null); - return success - ? ResponseEntity.ok().build() - : ResponseEntity.internalServerError() - .body(MessageUtil.getMessage("analyzer.lisaction.failed")); + + @PostMapping("/analyzer/runAction") + public ResponseEntity runAnalyzerAction(@RequestParam String analyzerType, + @RequestParam String actionName) { + AnalyzerImporterPlugin analyzerPlugin = pluginAnalyzerService.getPluginByAnalyzerId( + AnalyzerTestNameCache.getInstance().getAnalyzerIdForName(getAnalyzerNameFromType(analyzerType))); + if (analyzerPlugin instanceof BidirectionalAnalyzer) { + BidirectionalAnalyzer bidirectionalAnalyzer = (BidirectionalAnalyzer) analyzerPlugin; + boolean success = bidirectionalAnalyzer.runLISAction(actionName, null); + return success ? ResponseEntity.ok().build() + : ResponseEntity.internalServerError().body(MessageUtil.getMessage("analyzer.lisaction.failed")); + } + return ResponseEntity.badRequest().body(MessageUtil.getMessage("analyzer.lisaction.unsupported")); } - return ResponseEntity.badRequest() - .body(MessageUtil.getMessage("analyzer.lisaction.unsupported")); - } - - protected String getAnalyzerNameFromType(String analyzerType) { - String analyzer = null; - if (!GenericValidator.isBlankOrNull(analyzerType)) { - analyzer = AnalyzerTestNameCache.getInstance().getDBNameForActionName(analyzerType); + + protected String getAnalyzerNameFromType(String analyzerType) { + String analyzer = null; + if (!GenericValidator.isBlankOrNull(analyzerType)) { + analyzer = AnalyzerTestNameCache.getInstance().getDBNameForActionName(analyzerType); + } + return analyzer; } - return analyzer; - } - private String getSysUserId(HttpServletRequest request) { - UserSessionData usd = (UserSessionData) request.getAttribute(USER_SESSION_DATA); - if (usd == null) { - return null; + private String getSysUserId(HttpServletRequest request) { + UserSessionData usd = (UserSessionData) request.getAttribute(USER_SESSION_DATA); + if (usd == null) { + return null; + } + return String.valueOf(usd.getSystemUserId()); } - return String.valueOf(usd.getSystemUserId()); - } - - // private String getSysUserId(String user, String password) { - // LoginUser login = new LoginUser(); - // login.setLoginName(user); - // login.setPassword(password); - // - // login = loginService.getValidatedLogin(user, password).orElse(null); - // - // if (login != null) { - // SystemUser systemUser = systemUserService.getDataForLoginUser(login.getLoginName()); - // return systemUser.getId(); - // } - // - // return ""; - // } - // - // private boolean userValid(String user, String password) { - // LoginUser login = new LoginUser(); - // login.setLoginName(user); - // login.setPassword(password); - // - // login = loginService.getValidatedLogin(user, password).orElse(null); - // - // if (login == null) { - // return false; - // } else { - // return true; - // } - // } - - // private String streamToString(InputStream stream) throws IOException { - // StringBuilder builder = new StringBuilder(); - // int len; - // byte[] buffer = new byte[1024]; - // while ((len = stream.read(buffer, 0, buffer.length)) != -1) { - // builder.append(new String(buffer, 0, len, StandardCharsets.UTF_8)); - // } - // return builder.toString(); - // } - - // private String fieldStreamToString(InputStream stream) throws IOException { - // StringBuilder builder = new StringBuilder((int) (FIELD_SIZE_MAX / 2)); - // int len; - // byte[] buffer = new byte[32]; - // int totalFieldSize = 0; - // - // while ((len = stream.read(buffer, 0, buffer.length)) != -1) { - // builder.append(new String(buffer, 0, len, StandardCharsets.UTF_8)); - // totalFieldSize += len; - // if (totalFieldSize >= FIELD_SIZE_MAX) { - // break; - // } - // } - // return builder.toString(); - // } + + // private String getSysUserId(String user, String password) { + // LoginUser login = new LoginUser(); + // login.setLoginName(user); + // login.setPassword(password); + // + // login = loginService.getValidatedLogin(user, password).orElse(null); + // + // if (login != null) { + // SystemUser systemUser = + // systemUserService.getDataForLoginUser(login.getLoginName()); + // return systemUser.getId(); + // } + // + // return ""; + // } + // + // private boolean userValid(String user, String password) { + // LoginUser login = new LoginUser(); + // login.setLoginName(user); + // login.setPassword(password); + // + // login = loginService.getValidatedLogin(user, password).orElse(null); + // + // if (login == null) { + // return false; + // } else { + // return true; + // } + // } + + // private String streamToString(InputStream stream) throws IOException { + // StringBuilder builder = new StringBuilder(); + // int len; + // byte[] buffer = new byte[1024]; + // while ((len = stream.read(buffer, 0, buffer.length)) != -1) { + // builder.append(new String(buffer, 0, len, StandardCharsets.UTF_8)); + // } + // return builder.toString(); + // } + + // private String fieldStreamToString(InputStream stream) throws IOException { + // StringBuilder builder = new StringBuilder((int) (FIELD_SIZE_MAX / 2)); + // int len; + // byte[] buffer = new byte[32]; + // int totalFieldSize = 0; + // + // while ((len = stream.read(buffer, 0, buffer.length)) != -1) { + // builder.append(new String(buffer, 0, len, StandardCharsets.UTF_8)); + // totalFieldSize += len; + // if (totalFieldSize >= FIELD_SIZE_MAX) { + // break; + // } + // } + // return builder.toString(); + // } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/action/beans/NamedAnalyzerTestMapping.java b/src/main/java/org/openelisglobal/analyzerimport/action/beans/NamedAnalyzerTestMapping.java index 4382607201..738029e0ba 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/action/beans/NamedAnalyzerTestMapping.java +++ b/src/main/java/org/openelisglobal/analyzerimport/action/beans/NamedAnalyzerTestMapping.java @@ -17,49 +17,48 @@ public class NamedAnalyzerTestMapping { - private String analyzerName; - private String analyzerTestName; - private String actualTestName; - private String uniqueId; - private static final String uniqueIdSeperator = "#"; + private String analyzerName; + private String analyzerTestName; + private String actualTestName; + private String uniqueId; + private static final String uniqueIdSeperator = "#"; - public String getAnalyzerName() { - return analyzerName; - } + public String getAnalyzerName() { + return analyzerName; + } - public void setAnalyzerName(String analyzerName) { - this.analyzerName = analyzerName; - } + public void setAnalyzerName(String analyzerName) { + this.analyzerName = analyzerName; + } - public String getAnalyzerTestName() { - return analyzerTestName; - } + public String getAnalyzerTestName() { + return analyzerTestName; + } - public void setAnalyzerTestName(String analyzerTestName) { - this.analyzerTestName = analyzerTestName; - } + public void setAnalyzerTestName(String analyzerTestName) { + this.analyzerTestName = analyzerTestName; + } - public String getActualTestName() { - return actualTestName; - } + public String getActualTestName() { + return actualTestName; + } - public void setActualTestName(String actualTestName) { - this.actualTestName = actualTestName; - } + public void setActualTestName(String actualTestName) { + this.actualTestName = actualTestName; + } - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } - public String getUniqueId() { - if (uniqueId == null) { - uniqueId = - analyzerName + uniqueIdSeperator + analyzerTestName + uniqueIdSeperator + actualTestName; + public String getUniqueId() { + if (uniqueId == null) { + uniqueId = analyzerName + uniqueIdSeperator + analyzerTestName + uniqueIdSeperator + actualTestName; + } + return uniqueId; } - return uniqueId; - } - public static String getUniqueIdSeperator() { - return uniqueIdSeperator; - } + public static String getUniqueIdSeperator() { + return uniqueIdSeperator; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/ASTMAnalyzerReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/ASTMAnalyzerReader.java index 06fe12231b..9aa446f6e2 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/ASTMAnalyzerReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/ASTMAnalyzerReader.java @@ -28,123 +28,118 @@ public class ASTMAnalyzerReader extends AnalyzerReader { - private List lines; - private AnalyzerImporterPlugin plugin; - private AnalyzerLineInserter inserter; - private AnalyzerResponder responder; - private String error; - private boolean hasResponse = false; - private String responseBody; + private List lines; + private AnalyzerImporterPlugin plugin; + private AnalyzerLineInserter inserter; + private AnalyzerResponder responder; + private String error; + private boolean hasResponse = false; + private String responseBody; - @Override - public boolean readStream(InputStream stream) { - error = null; - inserter = null; - lines = new ArrayList<>(); - BufferedInputStream bis = new BufferedInputStream(stream); - CharsetDetector detector = new CharsetDetector(); - try { - detector.setText(bis); - String charsetName = detector.detect().getName(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bis, charsetName)); + @Override + public boolean readStream(InputStream stream) { + error = null; + inserter = null; + lines = new ArrayList<>(); + BufferedInputStream bis = new BufferedInputStream(stream); + CharsetDetector detector = new CharsetDetector(); + try { + detector.setText(bis); + String charsetName = detector.detect().getName(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bis, charsetName)); - try { - for (String line = bufferedReader.readLine(); - line != null; - line = bufferedReader.readLine()) { - lines.add(line); + try { + for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { + lines.add(line); + } + } catch (IOException e) { + error = "Unable to read input stream"; + LogEvent.logError(e); + return false; + } + } catch (IOException e) { + error = "Unable to determine message encoding"; + LogEvent.logError("an error occured detecting the encoding of the analyzer message", e); + return false; } - } catch (IOException e) { - error = "Unable to read input stream"; - LogEvent.logError(e); - return false; - } - } catch (IOException e) { - error = "Unable to determine message encoding"; - LogEvent.logError("an error occured detecting the encoding of the analyzer message", e); - return false; - } - if (!lines.isEmpty()) { - setInserterResponder(); - if (inserter == null) { - error = "Unable to understand which analyzer sent the message"; - return false; - } - return true; - } else { - error = "Empty message"; - return false; + if (!lines.isEmpty()) { + setInserterResponder(); + if (inserter == null) { + error = "Unable to understand which analyzer sent the message"; + return false; + } + return true; + } else { + error = "Empty message"; + return false; + } } - } - public boolean processData(String currentUserId) { - // it is assumed that all requests are either requests for information - // or analyzer results to be entered - if (plugin.isAnalyzerResult(lines)) { - return insertAnalyzerData(currentUserId); - } else { - responseBody = buildResponseForQuery(); - hasResponse = true; - return true; + public boolean processData(String currentUserId) { + // it is assumed that all requests are either requests for information + // or analyzer results to be entered + if (plugin.isAnalyzerResult(lines)) { + return insertAnalyzerData(currentUserId); + } else { + responseBody = buildResponseForQuery(); + hasResponse = true; + return true; + } } - } - public boolean hasResponse() { - return hasResponse; - } + public boolean hasResponse() { + return hasResponse; + } - public String getResponse() { - return responseBody; - } + public String getResponse() { + return responseBody; + } - private void setInserterResponder() { - for (AnalyzerImporterPlugin plugin : - SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { - if (plugin.isTargetAnalyzer(lines)) { - try { - this.plugin = plugin; - inserter = plugin.getAnalyzerLineInserter(); - responder = plugin.getAnalyzerResponder(); - return; - } catch (RuntimeException e) { - LogEvent.logError(e); + private void setInserterResponder() { + for (AnalyzerImporterPlugin plugin : SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { + if (plugin.isTargetAnalyzer(lines)) { + try { + this.plugin = plugin; + inserter = plugin.getAnalyzerLineInserter(); + responder = plugin.getAnalyzerResponder(); + return; + } catch (RuntimeException e) { + LogEvent.logError(e); + } + } } - } } - } - private String buildResponseForQuery() { - if (responder == null) { - error = - "Unable to understand which analyzer sent the query or plugin doesn't support responding"; - LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); - return ""; - } else { - LogEvent.logDebug( - this.getClass().getSimpleName(), "buildResponseForQuery", "building response"); - return responder.buildResponse(lines); + private String buildResponseForQuery() { + if (responder == null) { + error = "Unable to understand which analyzer sent the query or plugin doesn't support responding"; + LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); + return ""; + } else { + LogEvent.logDebug(this.getClass().getSimpleName(), "buildResponseForQuery", "building response"); + return responder.buildResponse(lines); + } } - } - @Override - public boolean insertAnalyzerData(String systemUserId) { - if (inserter == null) { - error = "Unable to understand which analyzer sent the file"; - LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); - return false; - } else { - boolean success = inserter.insert(lines, systemUserId); - if (!success) { - error = inserter.getError(); - LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); - } - return success; + @Override + public boolean insertAnalyzerData(String systemUserId) { + if (inserter == null) { + error = "Unable to understand which analyzer sent the file"; + LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); + return false; + } else { + boolean success = inserter.insert(lines, systemUserId); + if (!success) { + error = inserter.getError(); + LogEvent.logError(this.getClass().getSimpleName(), "buildResponseForQuery", error); + } + return success; + } } - } - @Override - public String getError() { - return error; - } + @Override + public String getError() { + return error; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineInserter.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineInserter.java index e498384c2f..c458b68e17 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineInserter.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineInserter.java @@ -24,34 +24,33 @@ public abstract class AnalyzerLineInserter { - protected AnalyzerResultsService analyzerResultService = - SpringContext.getBean(AnalyzerResultsService.class); + protected AnalyzerResultsService analyzerResultService = SpringContext.getBean(AnalyzerResultsService.class); - protected void persistResults(List results, String systemUserId) { - analyzerResultService.insertAnalyzerResults(results, systemUserId); - } - - protected boolean persistImport(String currentUserId, List results) { + protected void persistResults(List results, String systemUserId) { + analyzerResultService.insertAnalyzerResults(results, systemUserId); + } - if (results.size() > 0) { - for (AnalyzerResults analyzerResults : results) { - if (analyzerResults.getTestId().equals("-1")) { - analyzerResults.setTestId(null); - analyzerResults.setReadOnly(true); + protected boolean persistImport(String currentUserId, List results) { + + if (results.size() > 0) { + for (AnalyzerResults analyzerResults : results) { + if (analyzerResults.getTestId().equals("-1")) { + analyzerResults.setTestId(null); + analyzerResults.setReadOnly(true); + } + } + + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + return false; + } } - } - - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - LogEvent.logDebug(e); - return false; - } + return true; } - return true; - } - public abstract boolean insert(List lines, String currentUserId); + public abstract boolean insert(List lines, String currentUserId); - public abstract String getError(); + public abstract String getError(); } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineReader.java index 79da2237a0..3b3332e8b2 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerLineReader.java @@ -28,148 +28,138 @@ public class AnalyzerLineReader extends AnalyzerReader { - private static final String COBAS_INDICATOR = "COBAS INTEGRA400"; - private static final CharSequence SYSMEX_XT_INDICATOR = "XT-2000"; - private static final CharSequence FACSCALIBUR_INDICATOR = "MultiSET"; - private static final CharSequence EVOLIS_INTEGRAL_INDICATOR = - "DBehring Enzygnost HIV integral II"; - private static final CharSequence EVOLIS_INTEGRAL_DBS_INDICATOR = - "DBehring Enzygnost HIV integral IIDBS"; - private static final CharSequence EVOLIS_MUREX_INDICATOR = "Murex HIV 1_2"; - private static final CharSequence EVOLIS_MUREX_DBS_INDICATOR = "Murex HIV 1_2 DBS"; - private static final CharSequence COBAS_TAQMAN_INDICATOR = "HIV-HPS"; - private static final CharSequence COBAS_TAQMAN_INDICATOR_2 = "HIVHP2"; - private static final CharSequence COBAS_TAQMAN_INDICATOR_3 = "HI2CAP48"; - private static final CharSequence FACSCANTO_INDICATOR = "BD FACSCanto II"; - private static final CharSequence COBAS_TAQMAN_DBS_INDICATOR = "AMPLIPREP"; - private static final CharSequence COBAS_C311_INDICATOR = "R_Type1"; - private static final CharSequence MAURITUIS_INDICATOR = "R_Type1"; + private static final String COBAS_INDICATOR = "COBAS INTEGRA400"; + private static final CharSequence SYSMEX_XT_INDICATOR = "XT-2000"; + private static final CharSequence FACSCALIBUR_INDICATOR = "MultiSET"; + private static final CharSequence EVOLIS_INTEGRAL_INDICATOR = "DBehring Enzygnost HIV integral II"; + private static final CharSequence EVOLIS_INTEGRAL_DBS_INDICATOR = "DBehring Enzygnost HIV integral IIDBS"; + private static final CharSequence EVOLIS_MUREX_INDICATOR = "Murex HIV 1_2"; + private static final CharSequence EVOLIS_MUREX_DBS_INDICATOR = "Murex HIV 1_2 DBS"; + private static final CharSequence COBAS_TAQMAN_INDICATOR = "HIV-HPS"; + private static final CharSequence COBAS_TAQMAN_INDICATOR_2 = "HIVHP2"; + private static final CharSequence COBAS_TAQMAN_INDICATOR_3 = "HI2CAP48"; + private static final CharSequence FACSCANTO_INDICATOR = "BD FACSCanto II"; + private static final CharSequence COBAS_TAQMAN_DBS_INDICATOR = "AMPLIPREP"; + private static final CharSequence COBAS_C311_INDICATOR = "R_Type1"; + private static final CharSequence MAURITUIS_INDICATOR = "R_Type1"; - private List lines; - private AnalyzerLineInserter inserter; - private String error; + private List lines; + private AnalyzerLineInserter inserter; + private String error; - @Override - public boolean readStream(InputStream stream) { - error = null; - inserter = null; - lines = new ArrayList<>(); - BufferedInputStream bis = new BufferedInputStream(stream); - CharsetDetector detector = new CharsetDetector(); - try { - detector.setText(bis); - String charsetName = detector.detect().getName(); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bis, charsetName)); + @Override + public boolean readStream(InputStream stream) { + error = null; + inserter = null; + lines = new ArrayList<>(); + BufferedInputStream bis = new BufferedInputStream(stream); + CharsetDetector detector = new CharsetDetector(); + try { + detector.setText(bis); + String charsetName = detector.detect().getName(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bis, charsetName)); - try { - for (String line = bufferedReader.readLine(); - line != null; - line = bufferedReader.readLine()) { - lines.add(line); + try { + for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { + lines.add(line); + } + } catch (IOException e) { + error = "Unable to read file"; + LogEvent.logError("an error occured detecting the encoding of the analyzer file", e); + return false; + } + } catch (IOException e) { + error = "Unable to determine file encoding"; + LogEvent.logError("an error occured detecting the encoding of the analyzer file", e); + return false; } - } catch (IOException e) { - error = "Unable to read file"; - LogEvent.logError("an error occured detecting the encoding of the analyzer file", e); - return false; - } - } catch (IOException e) { - error = "Unable to determine file encoding"; - LogEvent.logError("an error occured detecting the encoding of the analyzer file", e); - return false; - } - if (!lines.isEmpty()) { - setInserter(); - if (inserter == null) { - error = "Unable to understand which analyzer sent the file"; - return false; - } - return true; - } else { - error = "Empty file"; - return false; + if (!lines.isEmpty()) { + setInserter(); + if (inserter == null) { + error = "Unable to understand which analyzer sent the file"; + return false; + } + return true; + } else { + error = "Empty file"; + return false; + } } - } - private void setInserter() { + private void setInserter() { - for (AnalyzerImporterPlugin plugin : - SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { - try { - if (plugin.isTargetAnalyzer(lines)) { - inserter = plugin.getAnalyzerLineInserter(); - return; + for (AnalyzerImporterPlugin plugin : SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { + try { + if (plugin.isTargetAnalyzer(lines)) { + inserter = plugin.getAnalyzerLineInserter(); + return; + } + } catch (RuntimeException e) { + LogEvent.logError(e); + } } - } catch (RuntimeException e) { - LogEvent.logError(e); - } - } - // This is going to be highly customized based on the characteristics of the - // file - // being sent + // This is going to be highly customized based on the characteristics of the + // file + // being sent - if (lines.get(0).contains(COBAS_INDICATOR)) { // Cobas is found on the first line - inserter = new CobasReader(); - } else if (lines.get(0).contains(EVOLIS_INTEGRAL_INDICATOR) - || lines.get(0).contains(EVOLIS_INTEGRAL_DBS_INDICATOR) - || lines.get(0).contains(EVOLIS_MUREX_INDICATOR) - || lines.get(0).contains(EVOLIS_MUREX_DBS_INDICATOR)) { // Evolis is found on the first line - inserter = new EvolisReader(); - } else if (lines.get(1) != null - && lines.get(1).contains(SYSMEX_XT_INDICATOR)) { // Sysmex model found on data - // line - inserter = new SysmexReader(); - } else if (lines.get(1) != null - && lines.get(1).contains(FACSCALIBUR_INDICATOR)) { // Fascalibur software found - // on data line - inserter = new FacscaliburReader(); - } else if (lines.get(1) != null - && (lines.get(1).contains(COBAS_TAQMAN_INDICATOR) - || lines.get(1).contains(COBAS_TAQMAN_INDICATOR_2) - || lines.get(1).contains(COBAS_TAQMAN_INDICATOR_3))) { - inserter = new CobasTaqmanReader(); - } else if (lines.get(1) != null && lines.get(1).contains(FACSCANTO_INDICATOR)) { - inserter = new FACSCantoReader(); - } else if (lines.get(1) != null - && lines.get(1).toUpperCase().contains(COBAS_TAQMAN_DBS_INDICATOR)) { - inserter = new CobasTaqmanDBSReader(); - } else { - // we're into squishy territory. It could be be TAQMAN with no test on first row - for (String line : lines) { - if (line.contains(COBAS_TAQMAN_INDICATOR) || line.contains(COBAS_TAQMAN_INDICATOR_2)) { - inserter = new CobasTaqmanReader(); + if (lines.get(0).contains(COBAS_INDICATOR)) { // Cobas is found on the first line + inserter = new CobasReader(); + } else if (lines.get(0).contains(EVOLIS_INTEGRAL_INDICATOR) + || lines.get(0).contains(EVOLIS_INTEGRAL_DBS_INDICATOR) || lines.get(0).contains(EVOLIS_MUREX_INDICATOR) + || lines.get(0).contains(EVOLIS_MUREX_DBS_INDICATOR)) { // Evolis is found on the first line + inserter = new EvolisReader(); + } else if (lines.get(1) != null && lines.get(1).contains(SYSMEX_XT_INDICATOR)) { // Sysmex model found on data + // line + inserter = new SysmexReader(); + } else if (lines.get(1) != null && lines.get(1).contains(FACSCALIBUR_INDICATOR)) { // Fascalibur software found + // on data line + inserter = new FacscaliburReader(); + } else if (lines.get(1) != null + && (lines.get(1).contains(COBAS_TAQMAN_INDICATOR) || lines.get(1).contains(COBAS_TAQMAN_INDICATOR_2) + || lines.get(1).contains(COBAS_TAQMAN_INDICATOR_3))) { + inserter = new CobasTaqmanReader(); + } else if (lines.get(1) != null && lines.get(1).contains(FACSCANTO_INDICATOR)) { + inserter = new FACSCantoReader(); + } else if (lines.get(1) != null && lines.get(1).toUpperCase().contains(COBAS_TAQMAN_DBS_INDICATOR)) { + inserter = new CobasTaqmanDBSReader(); + } else { + // we're into squishy territory. It could be be TAQMAN with no test on first row + for (String line : lines) { + if (line.contains(COBAS_TAQMAN_INDICATOR) || line.contains(COBAS_TAQMAN_INDICATOR_2)) { + inserter = new CobasTaqmanReader(); + } + } + if (inserter == null && lines.get(3).contains(COBAS_C311_INDICATOR)) { + inserter = new CobasC311Reader(); + } } - } - if (inserter == null && lines.get(3).contains(COBAS_C311_INDICATOR)) { - inserter = new CobasC311Reader(); - } } - } - /* - * For testing purposes only - */ - public void insertTestLines(List testLines) { - lines = testLines; - } + /* + * For testing purposes only + */ + public void insertTestLines(List testLines) { + lines = testLines; + } - @Override - public boolean insertAnalyzerData(String systemUserId) { - if (inserter == null) { - error = "Unable to understand which analyzer sent the file"; - return false; - } else { - boolean success = inserter.insert(lines, systemUserId); - if (!success) { - error = inserter.getError(); - } + @Override + public boolean insertAnalyzerData(String systemUserId) { + if (inserter == null) { + error = "Unable to understand which analyzer sent the file"; + return false; + } else { + boolean success = inserter.insert(lines, systemUserId); + if (!success) { + error = inserter.getError(); + } - return success; + return success; + } } - } - @Override - public String getError() { - return error; - } + @Override + public String getError() { + return error; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReader.java index b75cf2e435..df6d41e802 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReader.java @@ -19,9 +19,9 @@ public abstract class AnalyzerReader { - public abstract boolean readStream(InputStream stream); + public abstract boolean readStream(InputStream stream); - public abstract boolean insertAnalyzerData(String systemUserId); + public abstract boolean insertAnalyzerData(String systemUserId); - public abstract String getError(); + public abstract String getError(); } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderFactory.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderFactory.java index bddcf656d6..392f2081dd 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderFactory.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderFactory.java @@ -17,18 +17,18 @@ public class AnalyzerReaderFactory { - /* - * A little history. We have changed from a factory pattern to a strategy - * pattern but this is being left as a factory because we are assuming that at - * some point we are going to be reading more than flat files - */ - public static AnalyzerReader getReaderFor(String name) { - if (name.endsWith(".xls")) { - return new AnalyzerXLSLineReader(); + /* + * A little history. We have changed from a factory pattern to a strategy + * pattern but this is being left as a factory because we are assuming that at + * some point we are going to be reading more than flat files + */ + public static AnalyzerReader getReaderFor(String name) { + if (name.endsWith(".xls")) { + return new AnalyzerXLSLineReader(); + } + if (name.equals("astm")) { + return new ASTMAnalyzerReader(); + } + return new AnalyzerLineReader(); } - if (name.equals("astm")) { - return new ASTMAnalyzerReader(); - } - return new AnalyzerLineReader(); - } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderUtil.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderUtil.java index 41470b5a00..4da476c317 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderUtil.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerReaderUtil.java @@ -15,47 +15,43 @@ import org.openelisglobal.spring.util.SpringContext; public class AnalyzerReaderUtil { - // private SampleDAO sampleDAO = new SampleDAOImpl(); - // private AnalysisDAO analysisDAO = new AnalysisDAOImpl(); - // private ResultDAO resultDAO = new ResultDAOImpl(); + // private SampleDAO sampleDAO = new SampleDAOImpl(); + // private AnalysisDAO analysisDAO = new AnalysisDAOImpl(); + // private ResultDAO resultDAO = new ResultDAOImpl(); - protected SampleService sampleService = SpringContext.getBean(SampleService.class); - protected AnalysisService analysisService = SpringContext.getBean(AnalysisService.class); - protected ResultService resultService = SpringContext.getBean(ResultService.class); + protected SampleService sampleService = SpringContext.getBean(SampleService.class); + protected AnalysisService analysisService = SpringContext.getBean(AnalysisService.class); + protected ResultService resultService = SpringContext.getBean(ResultService.class); - public AnalyzerResults createAnalyzerResultFromDB(AnalyzerResults resultFromAnalyzer) { + public AnalyzerResults createAnalyzerResultFromDB(AnalyzerResults resultFromAnalyzer) { - Sample sample = - sampleService.getSampleByAccessionNumber(resultFromAnalyzer.getAccessionNumber()); + Sample sample = sampleService.getSampleByAccessionNumber(resultFromAnalyzer.getAccessionNumber()); - if (sample != null && sample.getId() != null) { - List analysisList = analysisService.getAnalysesBySampleId(sample.getId()); - String acceptedStatusId = - SpringContext.getBean(IStatusService.class) - .getStatusID(AnalysisStatus.TechnicalAcceptance); + if (sample != null && sample.getId() != null) { + List analysisList = analysisService.getAnalysesBySampleId(sample.getId()); + String acceptedStatusId = SpringContext.getBean(IStatusService.class) + .getStatusID(AnalysisStatus.TechnicalAcceptance); - for (Analysis analysis : analysisList) { - if (analysis.getStatusId().equals(acceptedStatusId) - && analysis.getTest().getId().equals(resultFromAnalyzer.getTestId())) { - List resultList = resultService.getResultsByAnalysis(analysis); - if (resultList.size() > 0) { - try { - AnalyzerResults resultFromDB = (AnalyzerResults) resultFromAnalyzer.clone(); - resultFromDB.setResult(resultList.get(resultList.size() - 1).getValue()); - resultFromDB.setCompleteDate( - analysis.getCompletedDate() == null - ? null - : new Timestamp(analysis.getCompletedDate().getTime())); - resultFromDB.setReadOnly(true); - resultFromDB.setResultType(resultFromAnalyzer.getResultType()); - return resultFromDB; - } catch (CloneNotSupportedException e) { - LogEvent.logDebug(e); + for (Analysis analysis : analysisList) { + if (analysis.getStatusId().equals(acceptedStatusId) + && analysis.getTest().getId().equals(resultFromAnalyzer.getTestId())) { + List resultList = resultService.getResultsByAnalysis(analysis); + if (resultList.size() > 0) { + try { + AnalyzerResults resultFromDB = (AnalyzerResults) resultFromAnalyzer.clone(); + resultFromDB.setResult(resultList.get(resultList.size() - 1).getValue()); + resultFromDB.setCompleteDate(analysis.getCompletedDate() == null ? null + : new Timestamp(analysis.getCompletedDate().getTime())); + resultFromDB.setReadOnly(true); + resultFromDB.setResultType(resultFromAnalyzer.getResultType()); + return resultFromDB; + } catch (CloneNotSupportedException e) { + LogEvent.logDebug(e); + } + } + } } - } } - } + return null; } - return null; - } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerResponder.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerResponder.java index bbdd39317b..c87f7a8f1b 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerResponder.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerResponder.java @@ -3,5 +3,5 @@ import java.util.List; public interface AnalyzerResponder { - public String buildResponse(List lines); + public String buildResponse(List lines); } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLLineReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLLineReader.java index f56d0afd18..c82389d945 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLLineReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLLineReader.java @@ -1,3 +1,4 @@ package org.openelisglobal.analyzerimport.analyzerreaders; -public class AnalyzerXLSLLineReader {} +public class AnalyzerXLSLLineReader { +} diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLineReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLineReader.java index b16dd16c22..24a6d0e6f1 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLineReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/AnalyzerXLSLineReader.java @@ -17,102 +17,101 @@ public class AnalyzerXLSLineReader extends AnalyzerReader { - private List lines; - private AnalyzerLineInserter inserter; - private String error; + private List lines; + private AnalyzerLineInserter inserter; + private String error; - @Override - public boolean readStream(InputStream stream) { - error = null; - inserter = null; - lines = new ArrayList<>(); - POIFSFileSystem fs = null; - HSSFWorkbook wb = null; - try { - fs = new POIFSFileSystem(stream); - wb = new HSSFWorkbook(fs); - HSSFSheet sheet = wb.getSheetAt(0); - Iterator rowIterator = sheet.rowIterator(); - while (rowIterator.hasNext()) { - Row row = rowIterator.next(); - Iterator cellIterator = row.cellIterator(); - String line = ""; - while (cellIterator.hasNext()) { - Cell cell = cellIterator.next(); - String value = ""; - switch (cell.getCellType()) { - case BLANK: - case STRING: - value = cell.getStringCellValue(); - break; - case NUMERIC: - value = Double.toString(cell.getNumericCellValue()); - break; - default: - } - line += value.replaceAll("\t", "\\t") + "\t"; + @Override + public boolean readStream(InputStream stream) { + error = null; + inserter = null; + lines = new ArrayList<>(); + POIFSFileSystem fs = null; + HSSFWorkbook wb = null; + try { + fs = new POIFSFileSystem(stream); + wb = new HSSFWorkbook(fs); + HSSFSheet sheet = wb.getSheetAt(0); + Iterator rowIterator = sheet.rowIterator(); + while (rowIterator.hasNext()) { + Row row = rowIterator.next(); + Iterator cellIterator = row.cellIterator(); + String line = ""; + while (cellIterator.hasNext()) { + Cell cell = cellIterator.next(); + String value = ""; + switch (cell.getCellType()) { + case BLANK: + case STRING: + value = cell.getStringCellValue(); + break; + case NUMERIC: + value = Double.toString(cell.getNumericCellValue()); + break; + default: + } + line += value.replaceAll("\t", "\\t") + "\t"; + } + if (line.endsWith("\t")) { + line = line.substring(0, line.length() - 1); + } + lines.add(line); + } + } catch (IOException e) { + error = "Unable to read file"; + return false; } - if (line.endsWith("\t")) { - line = line.substring(0, line.length() - 1); - } - lines.add(line); - } - } catch (IOException e) { - error = "Unable to read file"; - return false; - } - if (!lines.isEmpty()) { - setInserter(); - if (inserter == null) { - error = "Unable to understand which analyzer sent the file"; - return false; - } - return true; - } else { - error = "Empty file"; - return false; + if (!lines.isEmpty()) { + setInserter(); + if (inserter == null) { + error = "Unable to understand which analyzer sent the file"; + return false; + } + return true; + } else { + error = "Empty file"; + return false; + } } - } - private void setInserter() { - for (AnalyzerImporterPlugin plugin : - SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { - try { - if (plugin.isTargetAnalyzer(lines)) { - inserter = plugin.getAnalyzerLineInserter(); - return; + private void setInserter() { + for (AnalyzerImporterPlugin plugin : SpringContext.getBean(PluginAnalyzerService.class).getAnalyzerPlugins()) { + try { + if (plugin.isTargetAnalyzer(lines)) { + inserter = plugin.getAnalyzerLineInserter(); + return; + } + } catch (RuntimeException e) { + LogEvent.logError(e); + } } - } catch (RuntimeException e) { - LogEvent.logError(e); - } } - } - /* - * For testing purposes only - */ - public void insertTestLines(List testLines) { - lines = testLines; - } + /* + * For testing purposes only + */ + public void insertTestLines(List testLines) { + lines = testLines; + } - @Override - public boolean insertAnalyzerData(String systemUserId) { - if (inserter == null) { - error = "Unable to understand which analyzer sent the file"; - return false; - } else { - boolean success = inserter.insert(lines, systemUserId); - if (!success) { - error = inserter.getError(); - } + @Override + public boolean insertAnalyzerData(String systemUserId) { + if (inserter == null) { + error = "Unable to understand which analyzer sent the file"; + return false; + } else { + boolean success = inserter.insert(lines, systemUserId); + if (!success) { + error = inserter.getError(); + } - return success; + return success; + } } - } - @Override - public String getError() { - return error; - } + @Override + public String getError() { + return error; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasC311Reader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasC311Reader.java index f5d6c5954d..9ff43d7323 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasC311Reader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasC311Reader.java @@ -25,199 +25,179 @@ public class CobasC311Reader extends AnalyzerLineInserter { - private static final double ROUND_UP_KICKER = 0.000001; - private int ORDER_NUMBER = 0; - private int ORDER_DATE = 0; - private int ALTLIndex = 0; - private int ASTLIndex = 0; - private int creatininIndex = 0; - private int glycemiaIndex = 0; - - private static final String ALTL_NAME = "ALTL"; - private static final String ASTL_NAME = "ASTL"; - private static final String CREATININ_NAME = "Creatinin"; - private static final String GLYCEMIA_NAME = "Glycemia"; - private static final String DELIMITER = ","; - private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; - private static final String VALID_PREFIXES = "LART,LDBS,LRTN,LIND,LSPE"; - - private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - private String error; - - @Override - public boolean insert(List lines, String currentUserId) { - error = null; - boolean successful = true; - - List results = new ArrayList<>(); - - boolean columnsFound = manageColumns(lines.get(0), lines.get(3)); - - if (!columnsFound) { - error = "Cobas C311 analyzer: Unable to find correct columns in file"; - return false; + private static final double ROUND_UP_KICKER = 0.000001; + private int ORDER_NUMBER = 0; + private int ORDER_DATE = 0; + private int ALTLIndex = 0; + private int ASTLIndex = 0; + private int creatininIndex = 0; + private int glycemiaIndex = 0; + + private static final String ALTL_NAME = "ALTL"; + private static final String ASTL_NAME = "ASTL"; + private static final String CREATININ_NAME = "Creatinin"; + private static final String GLYCEMIA_NAME = "Glycemia"; + private static final String DELIMITER = ","; + private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; + private static final String VALID_PREFIXES = "LART,LDBS,LRTN,LIND,LSPE"; + + private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + private String error; + + @Override + public boolean insert(List lines, String currentUserId) { + error = null; + boolean successful = true; + + List results = new ArrayList<>(); + + boolean columnsFound = manageColumns(lines.get(0), lines.get(3)); + + if (!columnsFound) { + error = "Cobas C311 analyzer: Unable to find correct columns in file"; + return false; + } + + for (int i = 4; i < lines.size(); ++i) { + createAnalyzerResultFromLine(lines.get(i), results); + } + + if (results.size() > 0) { + + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + error = "Cobas Taqman DBS analyzer: Unable to save to database"; + successful = false; + } + } + + return successful; } - for (int i = 4; i < lines.size(); ++i) { - createAnalyzerResultFromLine(lines.get(i), results); + private boolean manageColumns(String line_1, String line_3) { + String[] fields = line_1.split(DELIMITER); + + for (int i = 0; i < fields.length; i++) { + String header = fields[i].replace("\"", ""); + if ("685".equals(header)) { + ALTLIndex = i - 1; + } else if ("687".equals(header)) { + ASTLIndex = i - 1; + } else if ("690".equals(header)) { + creatininIndex = i - 1; + } else if ("767".equals(header)) { + glycemiaIndex = i - 1; + } + } + + fields = line_3.split(DELIMITER); + + for (int i = 0; i < fields.length; i++) { + String header = fields[i].replace("\"", ""); + if ("S_ID".equals(header)) { + ORDER_NUMBER = i; + } else if ("M_Date".equals(header)) { + ORDER_DATE = i; + } + } + + return ORDER_DATE != 0 && ORDER_NUMBER != 0 && ALTLIndex != 0 && ASTLIndex != 0 && creatininIndex != 0 + && glycemiaIndex != 0; } - if (results.size() > 0) { + private void addValueToResults(List resultList, AnalyzerResults result) { + if (result != null) { + resultList.add(result); - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - error = "Cobas Taqman DBS analyzer: Unable to save to database"; - successful = false; - } + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); + if (resultFromDB != null) { + resultList.add(resultFromDB); + } + } } - return successful; - } - - private boolean manageColumns(String line_1, String line_3) { - String[] fields = line_1.split(DELIMITER); - - for (int i = 0; i < fields.length; i++) { - String header = fields[i].replace("\"", ""); - if ("685".equals(header)) { - ALTLIndex = i - 1; - } else if ("687".equals(header)) { - ASTLIndex = i - 1; - } else if ("690".equals(header)) { - creatininIndex = i - 1; - } else if ("767".equals(header)) { - glycemiaIndex = i - 1; - } + private void createAnalyzerResultFromLine(String line, List resultList) { + String[] fields = line.split(DELIMITER); + + if (fields.length <= ORDER_DATE) { + return; + } + + String accessionNumber = fields[ORDER_NUMBER].trim(); + Timestamp orderTimeStamp = DateUtil.convertStringDateToTimestampWithPattern(fields[ORDER_DATE].trim(), + DATE_PATTERN); + + addValueToResults(resultList, + createAnalyzerResult(ALTL_NAME, fields, ALTLIndex, accessionNumber, orderTimeStamp)); + addValueToResults(resultList, + createAnalyzerResult(ASTL_NAME, fields, ASTLIndex, accessionNumber, orderTimeStamp)); + addValueToResults(resultList, + createAnalyzerResult(CREATININ_NAME, fields, creatininIndex, accessionNumber, orderTimeStamp)); + addValueToResults(resultList, + createAnalyzerResult(GLYCEMIA_NAME, fields, glycemiaIndex, accessionNumber, orderTimeStamp)); } - fields = line_3.split(DELIMITER); + private AnalyzerResults createAnalyzerResult(String analyzerTestName, String[] fields, int index, + String accessionNumber, Timestamp orderTimeStamp) { - for (int i = 0; i < fields.length; i++) { - String header = fields[i].replace("\"", ""); - if ("S_ID".equals(header)) { - ORDER_NUMBER = i; - } else if ("M_Date".equals(header)) { - ORDER_DATE = i; - } - } - - return ORDER_DATE != 0 - && ORDER_NUMBER != 0 - && ALTLIndex != 0 - && ASTLIndex != 0 - && creatininIndex != 0 - && glycemiaIndex != 0; - } - - private void addValueToResults(List resultList, AnalyzerResults result) { - if (result != null) { - resultList.add(result); - - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); - if (resultFromDB != null) { - resultList.add(resultFromDB); - } - } - } + if (fields.length <= index) { + return null; + } - private void createAnalyzerResultFromLine(String line, List resultList) { - String[] fields = line.split(DELIMITER); + String result = fields[index].trim(); - if (fields.length <= ORDER_DATE) { - return; - } + if (GenericValidator.isBlankOrNull(result)) { + return null; + } - String accessionNumber = fields[ORDER_NUMBER].trim(); - Timestamp orderTimeStamp = - DateUtil.convertStringDateToTimestampWithPattern(fields[ORDER_DATE].trim(), DATE_PATTERN); - - addValueToResults( - resultList, - createAnalyzerResult(ALTL_NAME, fields, ALTLIndex, accessionNumber, orderTimeStamp)); - addValueToResults( - resultList, - createAnalyzerResult(ASTL_NAME, fields, ASTLIndex, accessionNumber, orderTimeStamp)); - addValueToResults( - resultList, - createAnalyzerResult( - CREATININ_NAME, fields, creatininIndex, accessionNumber, orderTimeStamp)); - addValueToResults( - resultList, - createAnalyzerResult( - GLYCEMIA_NAME, fields, glycemiaIndex, accessionNumber, orderTimeStamp)); - } - - private AnalyzerResults createAnalyzerResult( - String analyzerTestName, - String[] fields, - int index, - String accessionNumber, - Timestamp orderTimeStamp) { - - if (fields.length <= index) { - return null; - } + AnalyzerResults analyzerResults = new AnalyzerResults(); - String result = fields[index].trim(); + MappedTestName mappedName = AnalyzerTestNameCache.getInstance().getMappedTest(AnalyzerTestNameCache.COBAS_C311, + analyzerTestName); - if (GenericValidator.isBlankOrNull(result)) { - return null; - } + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance().getEmptyMappedTestName(AnalyzerTestNameCache.COBAS_C311, + analyzerTestName); + } - AnalyzerResults analyzerResults = new AnalyzerResults(); + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + analyzerResults.setResult(adjustResult(analyzerTestName, result)); + analyzerResults.setCompleteDate(orderTimeStamp); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setIsControl( + accessionNumber.length() < 9 || !VALID_PREFIXES.contains(accessionNumber.subSequence(0, 3))); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setResultType("N"); - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.COBAS_C311, analyzerTestName); + analyzerResults.setAccessionNumber(accessionNumber); - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName(AnalyzerTestNameCache.COBAS_C311, analyzerTestName); + return analyzerResults; } - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setResult(adjustResult(analyzerTestName, result)); - analyzerResults.setCompleteDate(orderTimeStamp); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setIsControl( - accessionNumber.length() < 9 - || !VALID_PREFIXES.contains(accessionNumber.subSequence(0, 3))); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setResultType("N"); + private String adjustResult(String analyzerTestName, String result) { - analyzerResults.setAccessionNumber(accessionNumber); + if (ALTL_NAME.equals(analyzerTestName)) { + return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)).split("\\.")[0]; + } - return analyzerResults; - } + if (ASTL_NAME.equals(analyzerTestName)) { + return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)).split("\\.")[0]; + } - private String adjustResult(String analyzerTestName, String result) { + if (CREATININ_NAME.equals(analyzerTestName)) { + return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 10.0)).split("\\.")[0]; + } - if (ALTL_NAME.equals(analyzerTestName)) { - return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)) - .split("\\.")[0]; - } - - if (ASTL_NAME.equals(analyzerTestName)) { - return String.valueOf(Math.rint(Double.parseDouble(result) + ROUND_UP_KICKER)) - .split("\\.")[0]; - } + if (GLYCEMIA_NAME.equals(analyzerTestName)) { + return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 100) / 100); + } - if (CREATININ_NAME.equals(analyzerTestName)) { - return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 10.0)) - .split("\\.")[0]; + return result; } - if (GLYCEMIA_NAME.equals(analyzerTestName)) { - return String.valueOf(Math.rint((Double.parseDouble(result) + ROUND_UP_KICKER) * 100) / 100); + @Override + public String getError() { + return error; } - - return result; - } - - @Override - public String getError() { - return error; - } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasReader.java index 122bb127f5..c6ceb19e53 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasReader.java @@ -28,156 +28,151 @@ public class CobasReader extends AnalyzerLineInserter { - protected TestService testService = SpringContext.getBean(TestService.class); - - private final String COBAS_INTEGRA400_NAME = "Cobas Integra"; - private String ASTL_ID; - private String ALTL_ID; - private String CRE_ID; - private String GLU_ID; - private Map testIdToPresentation; - - // private final int ID = 0; - private final int DATE = 1; - private final int TEST = 2; - // private final int BLANK1 = 3; - private final int ACCESSION = 4; - // private final int BLANK2 = 5; - // private final int SAMPLE_TYPE = 6; - private final int UNITS = 7; - // private final int BLANK3 = 8; - private final int MAJOR_RESULTS = 9; - // private final int MINOR_RESULTS = 10; - // private final int INDICATOR_1 = 11; - // private final int INDICATOR_2 = 12; - - private final String DELIMITER = "\\t"; - private final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; - private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - - public CobasReader() { - // TestDAO testDAO = new TestDAOImpl(); - ASTL_ID = testService.getActiveTestsByName("Transaminases ASTL").get(0).getId(); - ALTL_ID = testService.getActiveTestsByName("Transaminases ALTL").get(0).getId(); - CRE_ID = testService.getActiveTestsByName("Créatininémie").get(0).getId(); - GLU_ID = testService.getActiveTestsByName("Glycémie").get(0).getId(); - - testIdToPresentation = new HashMap<>(); - testIdToPresentation.put(ALTL_ID, 0); - testIdToPresentation.put(ASTL_ID, 1); - testIdToPresentation.put(CRE_ID, 2); - testIdToPresentation.put(GLU_ID, 3); - } - - @Override - public boolean insert(List lines, String currentUserId) { - boolean successful = true; - - if (lines == null) { - return true; + protected TestService testService = SpringContext.getBean(TestService.class); + + private final String COBAS_INTEGRA400_NAME = "Cobas Integra"; + private String ASTL_ID; + private String ALTL_ID; + private String CRE_ID; + private String GLU_ID; + private Map testIdToPresentation; + + // private final int ID = 0; + private final int DATE = 1; + private final int TEST = 2; + // private final int BLANK1 = 3; + private final int ACCESSION = 4; + // private final int BLANK2 = 5; + // private final int SAMPLE_TYPE = 6; + private final int UNITS = 7; + // private final int BLANK3 = 8; + private final int MAJOR_RESULTS = 9; + // private final int MINOR_RESULTS = 10; + // private final int INDICATOR_1 = 11; + // private final int INDICATOR_2 = 12; + + private final String DELIMITER = "\\t"; + private final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; + private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + + public CobasReader() { + // TestDAO testDAO = new TestDAOImpl(); + ASTL_ID = testService.getActiveTestsByName("Transaminases ASTL").get(0).getId(); + ALTL_ID = testService.getActiveTestsByName("Transaminases ALTL").get(0).getId(); + CRE_ID = testService.getActiveTestsByName("Créatininémie").get(0).getId(); + GLU_ID = testService.getActiveTestsByName("Glycémie").get(0).getId(); + + testIdToPresentation = new HashMap<>(); + testIdToPresentation.put(ALTL_ID, 0); + testIdToPresentation.put(ASTL_ID, 1); + testIdToPresentation.put(CRE_ID, 2); + testIdToPresentation.put(GLU_ID, 3); } - if (GenericValidator.isBlankOrNull(currentUserId)) { - return false; - } + @Override + public boolean insert(List lines, String currentUserId) { + boolean successful = true; - List results = new ArrayList<>(); - List notMatchedResults = new ArrayList<>(); + if (lines == null) { + return true; + } - Map accessionToResultMap = new HashMap<>(); - List accessionOrder = new ArrayList<>(); + if (GenericValidator.isBlankOrNull(currentUserId)) { + return false; + } - for (String line : lines) { - createAnalyzerResultFromLine(line, accessionToResultMap, accessionOrder, notMatchedResults); - } + List results = new ArrayList<>(); + List notMatchedResults = new ArrayList<>(); + + Map accessionToResultMap = new HashMap<>(); + List accessionOrder = new ArrayList<>(); - for (String accessionNumber : accessionOrder) { + for (String line : lines) { + createAnalyzerResultFromLine(line, accessionToResultMap, accessionOrder, notMatchedResults); + } + + for (String accessionNumber : accessionOrder) { + + AnalyzerResults[] resultSet = accessionToResultMap.get(accessionNumber); - AnalyzerResults[] resultSet = accessionToResultMap.get(accessionNumber); + for (int i = 0; i < 4; i++) { + if (resultSet[i] != null) { + addValueToResults(results, resultSet[i]); + } + } - for (int i = 0; i < 4; i++) { - if (resultSet[i] != null) { - addValueToResults(results, resultSet[i]); + for (AnalyzerResults analyzerResult : notMatchedResults) { + addValueToResults(results, analyzerResult); + } } - } - for (AnalyzerResults analyzerResult : notMatchedResults) { - addValueToResults(results, analyzerResult); - } + if (results.size() > 0) { + + // ensure transaction block + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + successful = false; + } + } + + return successful; } - if (results.size() > 0) { + private void addValueToResults(List resultList, AnalyzerResults result) { + resultList.add(result); - // ensure transaction block - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - successful = false; - } + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); + if (resultFromDB != null) { + resultList.add(resultFromDB); + } } - return successful; - } + private void createAnalyzerResultFromLine(String line, Map accessionToResultMap, + List accessionOrder, List notMatchedResults) { + String[] fields = line.split(DELIMITER); - private void addValueToResults(List resultList, AnalyzerResults result) { - resultList.add(result); + AnalyzerResults analyzerResults = new AnalyzerResults(); + MappedTestName mappedName = AnalyzerTestNameCache.getInstance().getMappedTest(COBAS_INTEGRA400_NAME, + fields[TEST]); - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); - if (resultFromDB != null) { - resultList.add(resultFromDB); - } - } - - private void createAnalyzerResultFromLine( - String line, - Map accessionToResultMap, - List accessionOrder, - List notMatchedResults) { - String[] fields = line.split(DELIMITER); - - AnalyzerResults analyzerResults = new AnalyzerResults(); - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance().getMappedTest(COBAS_INTEGRA400_NAME, fields[TEST]); - - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName(COBAS_INTEGRA400_NAME, fields[TEST]); - } + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance().getEmptyMappedTestName(COBAS_INTEGRA400_NAME, + fields[TEST]); + } - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setResult(fields[MAJOR_RESULTS]); - analyzerResults.setUnits(fields[UNITS]); - analyzerResults.setCompleteDate( - DateUtil.convertStringDateToTimestampWithPattern(fields[DATE], DATE_PATTERN)); - analyzerResults.setAccessionNumber(fields[ACCESSION]); - analyzerResults.setTestId(mappedName.getTestId()); - - if (analyzerResults.getAccessionNumber() != null) { - analyzerResults.setIsControl(analyzerResults.getAccessionNumber().trim().contains(" ")); - } else { - analyzerResults.setIsControl(false); - } + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + analyzerResults.setResult(fields[MAJOR_RESULTS]); + analyzerResults.setUnits(fields[UNITS]); + analyzerResults.setCompleteDate(DateUtil.convertStringDateToTimestampWithPattern(fields[DATE], DATE_PATTERN)); + analyzerResults.setAccessionNumber(fields[ACCESSION]); + analyzerResults.setTestId(mappedName.getTestId()); + + if (analyzerResults.getAccessionNumber() != null) { + analyzerResults.setIsControl(analyzerResults.getAccessionNumber().trim().contains(" ")); + } else { + analyzerResults.setIsControl(false); + } - analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); - if (analyzerResults.getTestId() != null) { - int bufferIndex = testIdToPresentation.get(analyzerResults.getTestId()).intValue(); - AnalyzerResults[] buffer = accessionToResultMap.get(analyzerResults.getAccessionNumber()); + if (analyzerResults.getTestId() != null) { + int bufferIndex = testIdToPresentation.get(analyzerResults.getTestId()).intValue(); + AnalyzerResults[] buffer = accessionToResultMap.get(analyzerResults.getAccessionNumber()); - if (buffer == null) { - buffer = new AnalyzerResults[4]; - accessionToResultMap.put(analyzerResults.getAccessionNumber(), buffer); - accessionOrder.add(analyzerResults.getAccessionNumber()); - } - buffer[bufferIndex] = analyzerResults; - } else { - notMatchedResults.add(analyzerResults); + if (buffer == null) { + buffer = new AnalyzerResults[4]; + accessionToResultMap.put(analyzerResults.getAccessionNumber(), buffer); + accessionOrder.add(analyzerResults.getAccessionNumber()); + } + buffer[bufferIndex] = analyzerResults; + } else { + notMatchedResults.add(analyzerResults); + } } - } - @Override - public String getError() { - return "Cobas Intgra 400 error writting to database"; - } + @Override + public String getError() { + return "Cobas Intgra 400 error writting to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanDBSReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanDBSReader.java index 1f57e0de6b..db87ed8bba 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanDBSReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanDBSReader.java @@ -30,158 +30,157 @@ public class CobasTaqmanDBSReader extends AnalyzerLineInserter { - protected DictionaryService dictionaryService = SpringContext.getBean(DictionaryService.class); - protected TestService testService = SpringContext.getBean(TestService.class); - protected TestResultService testResultService = SpringContext.getBean(TestResultService.class); - - private int ORDER_NUMBER = 0; - private int ORDER_DATE = 0; - private int RESULT = 0; - private int SAMPLE_TYPE = 0; - - private final String TEST_NAME = "HIQCAP48"; - private final String DELIMITER = "\\t"; - private final String DATE_PATTERN = "yyyy/MM/dd HH:mm:ss"; - private final String VALID_PREFIXES = "LART,LDBS,LRTN,LIND,LSPE"; - private String NEGATIVE_ID; - private String POSITIVE_ID; - - private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - private String error; - - public CobasTaqmanDBSReader() { - Test test = testService.getActiveTestsByName("DNA PCR").get(0); - List testResults = testResultService.getActiveTestResultsByTest(test.getId()); - - for (TestResult testResult : testResults) { - Dictionary dictionary = dictionaryService.getDataForId(testResult.getValue()); - if ("Positive".equals(dictionary.getDictEntry())) { - POSITIVE_ID = dictionary.getId(); - } else if ("Negative".equals(dictionary.getDictEntry())) { - NEGATIVE_ID = dictionary.getId(); - } + protected DictionaryService dictionaryService = SpringContext.getBean(DictionaryService.class); + protected TestService testService = SpringContext.getBean(TestService.class); + protected TestResultService testResultService = SpringContext.getBean(TestResultService.class); + + private int ORDER_NUMBER = 0; + private int ORDER_DATE = 0; + private int RESULT = 0; + private int SAMPLE_TYPE = 0; + + private final String TEST_NAME = "HIQCAP48"; + private final String DELIMITER = "\\t"; + private final String DATE_PATTERN = "yyyy/MM/dd HH:mm:ss"; + private final String VALID_PREFIXES = "LART,LDBS,LRTN,LIND,LSPE"; + private String NEGATIVE_ID; + private String POSITIVE_ID; + + private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + private String error; + + public CobasTaqmanDBSReader() { + Test test = testService.getActiveTestsByName("DNA PCR").get(0); + List testResults = testResultService.getActiveTestResultsByTest(test.getId()); + + for (TestResult testResult : testResults) { + Dictionary dictionary = dictionaryService.getDataForId(testResult.getValue()); + if ("Positive".equals(dictionary.getDictEntry())) { + POSITIVE_ID = dictionary.getId(); + } else if ("Negative".equals(dictionary.getDictEntry())) { + NEGATIVE_ID = dictionary.getId(); + } + } } - } - @Override - public boolean insert(List lines, String currentUserId) { - error = null; - boolean successful = true; + @Override + public boolean insert(List lines, String currentUserId) { + error = null; + boolean successful = true; + + List results = new ArrayList<>(); + + boolean columnsFound = manageColumns(lines.get(0)); + + if (!columnsFound) { + error = "Cobas Taqman DBS analyzer: Unable to find correct columns in file #"; + return false; + } + + MappedTestName mappedName = AnalyzerTestNameCache.getInstance().getMappedTest(AnalyzerTestNameCache.COBAS_DBS, + TEST_NAME); + + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance().getEmptyMappedTestName(AnalyzerTestNameCache.COBAS_DBS, + TEST_NAME); + } + + for (int i = 1; i < lines.size(); ++i) { + createAnalyzerResultFromLine(lines.get(i), results, mappedName); + } + + if (results.size() > 0) { + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + error = "Cobas Taqman DBS analyzer: Unable to save to database"; + successful = false; + } + } + return successful; + } - List results = new ArrayList<>(); + private boolean manageColumns(String line) { + String[] fields = line.split(DELIMITER); + + for (int i = 0; i < fields.length; i++) { + String header = fields[i].replace("\"", ""); + + if ("Order Number".equals(header)) { + ORDER_NUMBER = i; + } else if ("Order Date/Time".equals(header)) { + ORDER_DATE = i; + } else if ("Result".equals(header)) { + RESULT = i; + } else if ("Sample Type".equals(header)) { + SAMPLE_TYPE = i; + } + } + return ORDER_DATE != 0 && ORDER_NUMBER != 0 && RESULT != 0 && SAMPLE_TYPE != 0; + } - boolean columnsFound = manageColumns(lines.get(0)); + private void addValueToResults(List resultList, AnalyzerResults result) { + resultList.add(result); - if (!columnsFound) { - error = "Cobas Taqman DBS analyzer: Unable to find correct columns in file #"; - return false; + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); + if (resultFromDB != null) { + resultList.add(resultFromDB); + } } - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.COBAS_DBS, TEST_NAME); + private void createAnalyzerResultFromLine(String line, List resultList, + MappedTestName mappedName) { + String[] fields = line.split(DELIMITER); - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName(AnalyzerTestNameCache.COBAS_DBS, TEST_NAME); - } + AnalyzerResults analyzerResults = new AnalyzerResults(); - for (int i = 1; i < lines.size(); ++i) { - createAnalyzerResultFromLine(lines.get(i), results, mappedName); - } + String result = getAppropriateResults(fields[RESULT]); + String accessionNumber = fields[ORDER_NUMBER].replace("\"", "").trim(); - if (results.size() > 0) { - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - error = "Cobas Taqman DBS analyzer: Unable to save to database"; - successful = false; - } - } - return successful; - } - - private boolean manageColumns(String line) { - String[] fields = line.split(DELIMITER); - - for (int i = 0; i < fields.length; i++) { - String header = fields[i].replace("\"", ""); - - if ("Order Number".equals(header)) { - ORDER_NUMBER = i; - } else if ("Order Date/Time".equals(header)) { - ORDER_DATE = i; - } else if ("Result".equals(header)) { - RESULT = i; - } else if ("Sample Type".equals(header)) { - SAMPLE_TYPE = i; - } - } - return ORDER_DATE != 0 && ORDER_NUMBER != 0 && RESULT != 0 && SAMPLE_TYPE != 0; - } + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + analyzerResults.setResult(result); + analyzerResults.setCompleteDate(DateUtil + .convertStringDateToTimestampWithPattern(fields[ORDER_DATE].replace("\"", "").trim(), DATE_PATTERN)); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setIsControl(!VALID_PREFIXES.contains(accessionNumber.subSequence(0, 3))); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setResultType("D"); - private void addValueToResults(List resultList, AnalyzerResults result) { - resultList.add(result); + if (analyzerResults.getIsControl()) { + if (!"S".equals(fields[SAMPLE_TYPE].replace("\"", "").trim())) { + accessionNumber += ":" + fields[SAMPLE_TYPE].replace("\"", "").trim(); + } + } else { + accessionNumber = accessionNumber.substring(0, 9); + } - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); - if (resultFromDB != null) { - resultList.add(resultFromDB); - } - } - - private void createAnalyzerResultFromLine( - String line, List resultList, MappedTestName mappedName) { - String[] fields = line.split(DELIMITER); - - AnalyzerResults analyzerResults = new AnalyzerResults(); - - String result = getAppropriateResults(fields[RESULT]); - String accessionNumber = fields[ORDER_NUMBER].replace("\"", "").trim(); - - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setResult(result); - analyzerResults.setCompleteDate( - DateUtil.convertStringDateToTimestampWithPattern( - fields[ORDER_DATE].replace("\"", "").trim(), DATE_PATTERN)); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setIsControl(!VALID_PREFIXES.contains(accessionNumber.subSequence(0, 3))); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setResultType("D"); - - if (analyzerResults.getIsControl()) { - if (!"S".equals(fields[SAMPLE_TYPE].replace("\"", "").trim())) { - accessionNumber += ":" + fields[SAMPLE_TYPE].replace("\"", "").trim(); - } - } else { - accessionNumber = accessionNumber.substring(0, 9); + analyzerResults.setAccessionNumber(accessionNumber); + + addValueToResults(resultList, analyzerResults); } - analyzerResults.setAccessionNumber(accessionNumber); - - addValueToResults(resultList, analyzerResults); - } - - private String getAppropriateResults(String result) { - result = result.replace("\"", "").trim(); - if ("Target Not Detected".equals(result)) { - result = NEGATIVE_ID; - } else { - result = POSITIVE_ID; - // save this until we finish w/ requirements - // String workingResult = result.split("\\(")[0].replace("<", "").replace("E", ""); - // String[] splitResult = workingResult.split("\\+"); - // - // if (Double.parseDouble(splitResult[0]) * Math.pow(10, Double.parseDouble(splitResult[1])) - // < THREASHOLD) { - // result = UNDER_THREASHOLD; - // } + private String getAppropriateResults(String result) { + result = result.replace("\"", "").trim(); + if ("Target Not Detected".equals(result)) { + result = NEGATIVE_ID; + } else { + result = POSITIVE_ID; + // save this until we finish w/ requirements + // String workingResult = result.split("\\(")[0].replace("<", "").replace("E", + // ""); + // String[] splitResult = workingResult.split("\\+"); + // + // if (Double.parseDouble(splitResult[0]) * Math.pow(10, + // Double.parseDouble(splitResult[1])) + // < THREASHOLD) { + // result = UNDER_THREASHOLD; + // } + } + return result; } - return result; - } - @Override - public String getError() { - return error; - } + @Override + public String getError() { + return error; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanReader.java index 7d8445d341..eaa479533b 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/CobasTaqmanReader.java @@ -23,132 +23,124 @@ public class CobasTaqmanReader extends AnalyzerLineInserter { - private static final String UNDER_THREASHOLD = "< LL"; - private static final double THREASHOLD = 20.0; + private static final String UNDER_THREASHOLD = "< LL"; + private static final double THREASHOLD = 20.0; - @SuppressWarnings("unused") - private static final int PATIENT_NAME = 0; + @SuppressWarnings("unused") + private static final int PATIENT_NAME = 0; - @SuppressWarnings("unused") - private static final int PATIENT_ID = 1; + @SuppressWarnings("unused") + private static final int PATIENT_ID = 1; - @SuppressWarnings("unused") - private static final int ORDER_NUMBER = 2; + @SuppressWarnings("unused") + private static final int ORDER_NUMBER = 2; - private static final int ORDER_DATE = 3; - private static final int SAMPLE_ID = 4; - private static final int SAMPLE_TYPE = 5; + private static final int ORDER_DATE = 3; + private static final int SAMPLE_ID = 4; + private static final int SAMPLE_TYPE = 5; - @SuppressWarnings("unused") - private static final int BATCH_ID = 6; + @SuppressWarnings("unused") + private static final int BATCH_ID = 6; - private static final int TEST = 7; - private static final int RESULT = 8; - private static final int UNIT = 9; + private static final int TEST = 7; + private static final int RESULT = 8; + private static final int UNIT = 9; - private static final String DELIMITER = "\\t"; - private static final String ALT_DELIMITER = ","; - private static final String DATE_PATTERN = "yyyy/MM/dd HH:mm:ss"; - private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + private static final String DELIMITER = "\\t"; + private static final String ALT_DELIMITER = ","; + private static final String DATE_PATTERN = "yyyy/MM/dd HH:mm:ss"; + private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - @Override - public boolean insert(List lines, String currentUserId) { + @Override + public boolean insert(List lines, String currentUserId) { - boolean successful = true; + boolean successful = true; - List results = new ArrayList<>(); + List results = new ArrayList<>(); - for (int i = 1; i < lines.size(); ++i) { - createAnalyzerResultFromLine(lines.get(i), results); - } + for (int i = 1; i < lines.size(); ++i) { + createAnalyzerResultFromLine(lines.get(i), results); + } - if (results.size() > 0) { + if (results.size() > 0) { - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - successful = false; - } - } + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + successful = false; + } + } - return successful; - } + return successful; + } - private void addValueToResults(List resultList, AnalyzerResults result) { - resultList.add(result); + private void addValueToResults(List resultList, AnalyzerResults result) { + resultList.add(result); - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); - if (resultFromDB != null) { - resultList.add(resultFromDB); + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(result); + if (resultFromDB != null) { + resultList.add(resultFromDB); + } } - } - private void createAnalyzerResultFromLine(String line, List resultList) { - String[] fields = line.split(ALT_DELIMITER); - if (fields.length < 5) { - fields = line.split(DELIMITER); - } + private void createAnalyzerResultFromLine(String line, List resultList) { + String[] fields = line.split(ALT_DELIMITER); + if (fields.length < 5) { + fields = line.split(DELIMITER); + } - AnalyzerResults analyzerResults = new AnalyzerResults(); - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest( - AnalyzerTestNameCache.COBAS_TAQMAN, fields[TEST].replace("\"", "").trim()); - - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName( - AnalyzerTestNameCache.COBAS_TAQMAN, fields[TEST].replace("\"", "").trim()); + AnalyzerResults analyzerResults = new AnalyzerResults(); + MappedTestName mappedName = AnalyzerTestNameCache.getInstance() + .getMappedTest(AnalyzerTestNameCache.COBAS_TAQMAN, fields[TEST].replace("\"", "").trim()); + + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance().getEmptyMappedTestName(AnalyzerTestNameCache.COBAS_TAQMAN, + fields[TEST].replace("\"", "").trim()); + } + + String result = getAppropriateResults(fields[RESULT]); + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + analyzerResults.setResult(result); + analyzerResults.setUnits(UNDER_THREASHOLD.equals(result) ? "" : fields[UNIT].replace("\"", "").trim()); + analyzerResults.setCompleteDate(DateUtil + .convertStringDateToTimestampWithPattern(fields[ORDER_DATE].replace("\"", "").trim(), DATE_PATTERN)); + analyzerResults.setAccessionNumber(fields[SAMPLE_ID].replace("\"", "").trim()); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setIsControl(!"S".equals(fields[SAMPLE_TYPE].replace("\"", "").trim())); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setResultType("A"); + + addValueToResults(resultList, analyzerResults); } - String result = getAppropriateResults(fields[RESULT]); - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setResult(result); - analyzerResults.setUnits( - UNDER_THREASHOLD.equals(result) ? "" : fields[UNIT].replace("\"", "").trim()); - analyzerResults.setCompleteDate( - DateUtil.convertStringDateToTimestampWithPattern( - fields[ORDER_DATE].replace("\"", "").trim(), DATE_PATTERN)); - analyzerResults.setAccessionNumber(fields[SAMPLE_ID].replace("\"", "").trim()); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setIsControl(!"S".equals(fields[SAMPLE_TYPE].replace("\"", "").trim())); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setResultType("A"); - - addValueToResults(resultList, analyzerResults); - } - - private String getAppropriateResults(String result) { - result = result.replace("\"", "").trim(); - if ("Target Not Detected".equalsIgnoreCase(result) || "Below range".equalsIgnoreCase(result)) { - result = UNDER_THREASHOLD; - } else { - - String workingResult = result.split("\\(")[0].replace("<", "").replace("E", ""); - String[] splitResult = workingResult.split("\\+"); - - try { - Double resultAsDouble = - Double.parseDouble(splitResult[0]) * Math.pow(10, Double.parseDouble(splitResult[1])); - - if (resultAsDouble <= THREASHOLD) { - result = UNDER_THREASHOLD; + private String getAppropriateResults(String result) { + result = result.replace("\"", "").trim(); + if ("Target Not Detected".equalsIgnoreCase(result) || "Below range".equalsIgnoreCase(result)) { + result = UNDER_THREASHOLD; } else { - result = - String.valueOf((int) (Math.round(resultAsDouble))) - + result.substring(result.indexOf("(")); + + String workingResult = result.split("\\(")[0].replace("<", "").replace("E", ""); + String[] splitResult = workingResult.split("\\+"); + + try { + Double resultAsDouble = Double.parseDouble(splitResult[0]) + * Math.pow(10, Double.parseDouble(splitResult[1])); + + if (resultAsDouble <= THREASHOLD) { + result = UNDER_THREASHOLD; + } else { + result = String.valueOf((int) (Math.round(resultAsDouble))) + result.substring(result.indexOf("(")); + } + } catch (NumberFormatException e) { + return "XXXX"; + } } - } catch (NumberFormatException e) { - return "XXXX"; - } - } - return result; - } + return result; + } - @Override - public String getError() { - return "Cobas Taqman unable to write to database"; - } + @Override + public String getError() { + return "Cobas Taqman unable to write to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/EvolisReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/EvolisReader.java index 3abdee4d24..beb5efed36 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/EvolisReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/EvolisReader.java @@ -33,116 +33,110 @@ public class EvolisReader extends AnalyzerLineInserter { - protected DictionaryService dictionaryService = SpringContext.getBean(DictionaryService.class); - protected TestService testService = SpringContext.getBean(TestService.class); - protected TestResultService testResultService = SpringContext.getBean(TestResultService.class); - - private String NEGATIVE_DICTIONARY_ID = null; - private String POSITIVE_DICTIONARY_ID = null; - private String INDETERMINATE_DICTIONARY_ID = null; - private String DELIMITER = "|"; - private int Id = 0; - private int assay = 1; - private int well = 2; - private int flag = 3; - private int value = 4; - private int S_CO = 5; - private int result = 6; - - private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - - public EvolisReader() { - Test test = - testService.getTestByLocalizedName( - "Integral", Locale.ENGLISH); // integral and murex use the same - // dictionary values - - List testResults = testResultService.getActiveTestResultsByTest(test.getId()); - - for (TestResult testResult : testResults) { - String dictionaryValue = - dictionaryService.getDictionaryById(testResult.getValue()).getDictEntry(); - - if ("Positive".equals(dictionaryValue)) { - POSITIVE_DICTIONARY_ID = testResult.getValue(); - } else if ("Negative".equals(dictionaryValue)) { - NEGATIVE_DICTIONARY_ID = testResult.getValue(); - } else if ("Indeterminate".equals(dictionaryValue)) { - INDETERMINATE_DICTIONARY_ID = testResult.getValue(); - } + protected DictionaryService dictionaryService = SpringContext.getBean(DictionaryService.class); + protected TestService testService = SpringContext.getBean(TestService.class); + protected TestResultService testResultService = SpringContext.getBean(TestResultService.class); + + private String NEGATIVE_DICTIONARY_ID = null; + private String POSITIVE_DICTIONARY_ID = null; + private String INDETERMINATE_DICTIONARY_ID = null; + private String DELIMITER = "|"; + private int Id = 0; + private int assay = 1; + private int well = 2; + private int flag = 3; + private int value = 4; + private int S_CO = 5; + private int result = 6; + + private AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + + public EvolisReader() { + Test test = testService.getTestByLocalizedName("Integral", Locale.ENGLISH); // integral and murex use the same + // dictionary values + + List testResults = testResultService.getActiveTestResultsByTest(test.getId()); + + for (TestResult testResult : testResults) { + String dictionaryValue = dictionaryService.getDictionaryById(testResult.getValue()).getDictEntry(); + + if ("Positive".equals(dictionaryValue)) { + POSITIVE_DICTIONARY_ID = testResult.getValue(); + } else if ("Negative".equals(dictionaryValue)) { + NEGATIVE_DICTIONARY_ID = testResult.getValue(); + } else if ("Indeterminate".equals(dictionaryValue)) { + INDETERMINATE_DICTIONARY_ID = testResult.getValue(); + } + } } - } - @Override - public boolean insert(List lines, String currentUserId) { + @Override + public boolean insert(List lines, String currentUserId) { - boolean successful = true; + boolean successful = true; - List results = new ArrayList<>(); + List results = new ArrayList<>(); - for (int i = 1; i < lines.size(); i++) { - addAnalyzerResultFromLine(results, lines.get(i)); - } + for (int i = 1; i < lines.size(); i++) { + addAnalyzerResultFromLine(results, lines.get(i)); + } - if (results.size() > 0) { + if (results.size() > 0) { - // ensure transaction block - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - LogEvent.logDebug(e); - successful = false; - } - } - return successful; - } - - private void addAnalyzerResultFromLine(List results, String line) { - line = line.replace("\"", "").replace(DELIMITER, ":"); - String[] fields = line.split(":"); - - String analyzerAccessionNumber = fields[Id]; - - if (fields.length == 7 - && !GenericValidator.isBlankOrNull(analyzerAccessionNumber) - && analyzerAccessionNumber.length() > 6 - && fields[assay].length() > 5) { - - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.EVOLIS, fields[assay]); - AnalyzerResults analyzerResults = new AnalyzerResults(); - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setResult(getDictioanryValueForResult(fields[result])); - analyzerResults.setResultType("D"); - analyzerResults.setCompleteDate(new Timestamp(new Date().getTime())); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setAccessionNumber(analyzerAccessionNumber); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setIsControl(false); - results.add(analyzerResults); - - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); - if (resultFromDB != null) { - results.add(resultFromDB); - } + // ensure transaction block + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + successful = false; + } + } + return successful; } - } - - private String getDictioanryValueForResult(String result) { - if ("NEG".equals(result)) { - return NEGATIVE_DICTIONARY_ID; - } else if ("REACTIVE".equals(result)) { - return POSITIVE_DICTIONARY_ID; - } else if ("*".equals(result)) { - return INDETERMINATE_DICTIONARY_ID; + + private void addAnalyzerResultFromLine(List results, String line) { + line = line.replace("\"", "").replace(DELIMITER, ":"); + String[] fields = line.split(":"); + + String analyzerAccessionNumber = fields[Id]; + + if (fields.length == 7 && !GenericValidator.isBlankOrNull(analyzerAccessionNumber) + && analyzerAccessionNumber.length() > 6 && fields[assay].length() > 5) { + + MappedTestName mappedName = AnalyzerTestNameCache.getInstance().getMappedTest(AnalyzerTestNameCache.EVOLIS, + fields[assay]); + AnalyzerResults analyzerResults = new AnalyzerResults(); + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + analyzerResults.setResult(getDictioanryValueForResult(fields[result])); + analyzerResults.setResultType("D"); + analyzerResults.setCompleteDate(new Timestamp(new Date().getTime())); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setAccessionNumber(analyzerAccessionNumber); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setIsControl(false); + results.add(analyzerResults); + + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); + if (resultFromDB != null) { + results.add(resultFromDB); + } + } } - return null; - } + private String getDictioanryValueForResult(String result) { + if ("NEG".equals(result)) { + return NEGATIVE_DICTIONARY_ID; + } else if ("REACTIVE".equals(result)) { + return POSITIVE_DICTIONARY_ID; + } else if ("*".equals(result)) { + return INDETERMINATE_DICTIONARY_ID; + } - @Override - public String getError() { - return "Evolis analyzer unable to write to database"; - } + return null; + } + + @Override + public String getError() { + return "Evolis analyzer unable to write to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FACSCantoReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FACSCantoReader.java index 87a37a9550..3a9a6e5442 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FACSCantoReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FACSCantoReader.java @@ -26,160 +26,154 @@ public class FACSCantoReader extends AnalyzerLineInserter { - private static final String CONTROL_ACCESSION_PREFIX = "IMM"; + private static final String CONTROL_ACCESSION_PREFIX = "IMM"; - private static final String SAMPLE_ID_HEADER = "Sample ID"; - private static final String DATE_ANALYZED_HEADER = "Date Analyzed"; - private static final String CD3_CD8_CD45_CD4_CD3_PER_LYMPHS_HEADER = - "CD3/CD8/CD45/CD4 CD3+ %Lymphs"; - private static final String CD3_CD8_CD45_CD4_CD3_CD4_PER_LYMPHS_HEADER = - "CD3/CD8/CD45/CD4 CD3+CD4+ %Lymphs"; + private static final String SAMPLE_ID_HEADER = "Sample ID"; + private static final String DATE_ANALYZED_HEADER = "Date Analyzed"; + private static final String CD3_CD8_CD45_CD4_CD3_PER_LYMPHS_HEADER = "CD3/CD8/CD45/CD4 CD3+ %Lymphs"; + private static final String CD3_CD8_CD45_CD4_CD3_CD4_PER_LYMPHS_HEADER = "CD3/CD8/CD45/CD4 CD3+CD4+ %Lymphs"; - private static final String DATE_PATTERN = "MM/dd/yyyy HH:mm"; + private static final String DATE_PATTERN = "MM/dd/yyyy HH:mm"; - private int Sample_ID; - private int Date_Analyzed; - private int CD3_CD8_CD45_CD4_CD3_perLymphs; - private int CD3_CD8_CD45_CD4_CD3_CD4_perLymphs; - private String[] testNameIndex; - private String[] unitsIndex; - private int maxViewedIndex = 0; + private int Sample_ID; + private int Date_Analyzed; + private int CD3_CD8_CD45_CD4_CD3_perLymphs; + private int CD3_CD8_CD45_CD4_CD3_CD4_perLymphs; + private String[] testNameIndex; + private String[] unitsIndex; + private int maxViewedIndex = 0; - @Override - public boolean insert(List lines, String currentUserId) { + @Override + public boolean insert(List lines, String currentUserId) { - boolean successful = true; + boolean successful = true; - List results = new ArrayList<>(); + List results = new ArrayList<>(); - manageColumns(lines.get(0)); + manageColumns(lines.get(0)); - for (int i = 1; i < lines.size(); i++) { - addAnalyzerResultFromLine(results, lines.get(i)); - } + for (int i = 1; i < lines.size(); i++) { + addAnalyzerResultFromLine(results, lines.get(i)); + } - if (results.size() > 0) { + if (results.size() > 0) { + + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + successful = false; + } + } - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - successful = false; - } + return successful; } - return successful; - } + private void manageColumns(String line) { + String[] fields = StringUtil.separateCSVWithEmbededQuotes(line); + if (fields.length < 10) { + fields = line.split(","); + } - private void manageColumns(String line) { - String[] fields = StringUtil.separateCSVWithEmbededQuotes(line); - if (fields.length < 10) { - fields = line.split(","); - } + for (int i = 0; i < fields.length; i++) { + String header = fields[i].replace("\"", ""); + + if (SAMPLE_ID_HEADER.equals(header)) { + Sample_ID = i; + maxViewedIndex = Math.max(maxViewedIndex, i); + } else if (DATE_ANALYZED_HEADER.equals(header)) { + Date_Analyzed = i; + maxViewedIndex = Math.max(maxViewedIndex, i); + } else if (CD3_CD8_CD45_CD4_CD3_CD4_PER_LYMPHS_HEADER.equals(header)) { + CD3_CD8_CD45_CD4_CD3_CD4_perLymphs = i; + maxViewedIndex = Math.max(maxViewedIndex, i); + } else if (CD3_CD8_CD45_CD4_CD3_PER_LYMPHS_HEADER.equals(header)) { + CD3_CD8_CD45_CD4_CD3_perLymphs = i; + maxViewedIndex = Math.max(maxViewedIndex, i); + } + } - for (int i = 0; i < fields.length; i++) { - String header = fields[i].replace("\"", ""); - - if (SAMPLE_ID_HEADER.equals(header)) { - Sample_ID = i; - maxViewedIndex = Math.max(maxViewedIndex, i); - } else if (DATE_ANALYZED_HEADER.equals(header)) { - Date_Analyzed = i; - maxViewedIndex = Math.max(maxViewedIndex, i); - } else if (CD3_CD8_CD45_CD4_CD3_CD4_PER_LYMPHS_HEADER.equals(header)) { - CD3_CD8_CD45_CD4_CD3_CD4_perLymphs = i; - maxViewedIndex = Math.max(maxViewedIndex, i); - } else if (CD3_CD8_CD45_CD4_CD3_PER_LYMPHS_HEADER.equals(header)) { - CD3_CD8_CD45_CD4_CD3_perLymphs = i; - maxViewedIndex = Math.max(maxViewedIndex, i); - } - } + testNameIndex = new String[fields.length]; + unitsIndex = new String[fields.length]; - testNameIndex = new String[fields.length]; - unitsIndex = new String[fields.length]; + testNameIndex[CD3_CD8_CD45_CD4_CD3_perLymphs] = "CD3_PER"; + testNameIndex[CD3_CD8_CD45_CD4_CD3_CD4_perLymphs] = "CD4_PER"; - testNameIndex[CD3_CD8_CD45_CD4_CD3_perLymphs] = "CD3_PER"; - testNameIndex[CD3_CD8_CD45_CD4_CD3_CD4_perLymphs] = "CD4_PER"; + unitsIndex[CD3_CD8_CD45_CD4_CD3_perLymphs] = "%"; + unitsIndex[CD3_CD8_CD45_CD4_CD3_CD4_perLymphs] = "%"; + } - unitsIndex[CD3_CD8_CD45_CD4_CD3_perLymphs] = "%"; - unitsIndex[CD3_CD8_CD45_CD4_CD3_CD4_perLymphs] = "%"; - } + private void addAnalyzerResultFromLine(List results, String line) { + String[] fields = StringUtil.separateCSVWithMixedEmbededQuotes(line); - private void addAnalyzerResultFromLine(List results, String line) { - String[] fields = StringUtil.separateCSVWithMixedEmbededQuotes(line); + // This insures that the row has not been truncated + if (fields.length < maxViewedIndex) { + return; + } - // This insures that the row has not been truncated - if (fields.length < maxViewedIndex) { - return; - } + AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + String analyzerAccessionNumber = fields[Sample_ID].replace("\"", ""); + analyzerAccessionNumber = StringUtil.strip(analyzerAccessionNumber, " "); - AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - String analyzerAccessionNumber = fields[Sample_ID].replace("\"", ""); - analyzerAccessionNumber = StringUtil.strip(analyzerAccessionNumber, " "); + String date = fields[Date_Analyzed].replace("\"", ""); - String date = fields[Date_Analyzed].replace("\"", ""); + // this is sort of dumb, we have the indexes we are interested in + for (int i = 0; i < testNameIndex.length; i++) { + if (!GenericValidator.isBlankOrNull(testNameIndex[i])) { + MappedTestName mappedName = AnalyzerTestNameCache.getInstance() + .getMappedTest(AnalyzerTestNameCache.FACSCANTO, testNameIndex[i].replace("\"", "")); - // this is sort of dumb, we have the indexes we are interested in - for (int i = 0; i < testNameIndex.length; i++) { - if (!GenericValidator.isBlankOrNull(testNameIndex[i])) { - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.FACSCANTO, testNameIndex[i].replace("\"", "")); + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance().getEmptyMappedTestName( + AnalyzerTestNameCache.FACSCANTO, testNameIndex[i].replace("\"", "")); + } - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName( - AnalyzerTestNameCache.FACSCANTO, testNameIndex[i].replace("\"", "")); - } + AnalyzerResults analyzerResults = new AnalyzerResults(); - AnalyzerResults analyzerResults = new AnalyzerResults(); + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + String result = fields[i].replace("\"", ""); + result = roundTwoDigits(result); + analyzerResults.setResult(result); + analyzerResults.setUnits(unitsIndex[i]); - String result = fields[i].replace("\"", ""); - result = roundTwoDigits(result); - analyzerResults.setResult(result); - analyzerResults.setUnits(unitsIndex[i]); + analyzerResults + .setCompleteDate(DateUtil.convertStringDateToTimestampWithPatternNoLocale(date, DATE_PATTERN)); + // analyzerResults.setCompleteTime(DateUtil.convertStringDateToTimestamp(date)); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setAccessionNumber(analyzerAccessionNumber); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setCompleteDate( - DateUtil.convertStringDateToTimestampWithPatternNoLocale(date, DATE_PATTERN)); - // analyzerResults.setCompleteTime(DateUtil.convertStringDateToTimestamp(date)); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setAccessionNumber(analyzerAccessionNumber); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); + if (analyzerAccessionNumber != null) { + analyzerResults.setIsControl(analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); + } else { + analyzerResults.setIsControl(false); + } - if (analyzerAccessionNumber != null) { - analyzerResults.setIsControl( - analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); - } else { - analyzerResults.setIsControl(false); + results.add(analyzerResults); + + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); + if (resultFromDB != null) { + results.add(resultFromDB); + } + } } + } - results.add(analyzerResults); + private String roundTwoDigits(String result) { - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); - if (resultFromDB != null) { - results.add(resultFromDB); + try { + Double doubleResult = Double.parseDouble(result); + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb); + formatter.format("%.2f", (Math.rint(doubleResult * 100.0) / 100.0)); + return sb.toString(); + } catch (NumberFormatException e) { + return result; } - } } - } - - private String roundTwoDigits(String result) { - - try { - Double doubleResult = Double.parseDouble(result); - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb); - formatter.format("%.2f", (Math.rint(doubleResult * 100.0) / 100.0)); - return sb.toString(); - } catch (NumberFormatException e) { - return result; - } - } - @Override - public String getError() { - return "FacsCANTO analyzer unable to write to database"; - } + @Override + public String getError() { + return "FacsCANTO analyzer unable to write to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FacscaliburReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FacscaliburReader.java index 87f6efda7d..df315d569e 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FacscaliburReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/FacscaliburReader.java @@ -26,196 +26,190 @@ @SuppressWarnings("unused") public class FacscaliburReader extends AnalyzerLineInserter { - private static final String CONTROL_ACCESSION_PREFIX = "IMM"; - - private static int index = 0; - private static final int Institution = index++; - private static final int Director = index++; - private static final int Operator = index++; - private static final int Cytometer = index++; - private static final int Cytometer_Serial_Number = index++; - private static final int Software_Version = index++; - private static final int Sample_Name = index++; - private static final int Sample_ID = index++; - private static final int Case_Number = index++; - private static final int Column_1 = index++; - private static final int Column_2 = index++; - private static final int Column_3 = index++; - private static final int Panel_Name = index++; - private static final int Collection_Date = index++; - private static final int Date_Analyzed = index++; - private static final int Lab_Report_File_Name = index++; - private static final int Physicians_Report_File_Name = index++; - private static final int WBC_Count_x1000 = index++; - private static final int Lymphs_per = index++; - private static final int Lymphs_x1000 = index++; - private static final int Abs_Cnt_Bead_Name = index++; - private static final int Abs_Cnt_Bead_Lot_ID = index++; - private static final int Abs_Cnt_Beads_Pellet = index++; - private static final int Control_Bead_Name = index++; - private static final int Control_Bead_Lot_ID = index++; - private static final int Control_Low_Beads_µL = index++; - private static final int Control_Medium_Beads_µL = index++; - private static final int Control_High_Beads_µL = index++; - private static final int Control_Low_SD = index++; - private static final int Control_Medium_SD = index++; - private static final int Control_High_SD = index++; - private static final int Ref_Range = index++; - private static final int Comments = index++; - private static final int Lymphosum = index++; - private static final int CD3_per_Lymph_Difference = index++; - private static final int T_Helper_Suppressor_Ratio = index++; - private static final int Min_CD3_Abs_Cnt_Range = index++; - private static final int Max_CD3_Abs_Cnt_Range = index++; - private static final int Avg_CD3_CD4_per_T_Lymph = index++; - private static final int Avg_CD3_CD8__per_T_Lymph = index++; - private static final int Avg_CD3_CD4_CD8__per_T_Lymph = index++; - private static final int Avg_CD3__per_Lymph = index++; - private static final int Avg_CD3__Abs_Cnt = index++; - private static final int Avg_CD3_CD4__per_Lymph = index++; - private static final int Avg_CD3_CD4__Abs_Cnt = index++; - private static final int Avg_CD3_CD8__per_Lymph = index++; - private static final int Avg_CD3_CD8__Abs_Cnt = index++; - private static final int Avg_CD3_CD4_CD8__per_Lymph = index++; - private static final int Avg_CD3_CD4_CD8__Abs_Cnt = index++; - private static final int Avg_CD19__per_Lymph = index++; - private static final int Avg_CD19__Abs_Cnt = index++; - private static final int Avg_CD16_56__per_Lymph = index++; - private static final int Avg_CD16_56__Abs_Cnt = index++; - private static final int CD45__Abs_Cnt = index++; - private static final int CD3_CD4_CD45_FCS_File_Name = index++; - private static final int CD3_CD4_CD45_Lot_ID = index++; - private static final int CD3_CD4_CD45_Collection_Time = index++; - private static final int CD3_CD4_CD45_Total_Events = index++; - private static final int CD3_CD4_CD45_Tube_Name = index++; - private static final int CD3_CD4_CD45_Attr_Def_File_Name = index++; - private static final int CD3_CD4_CD45_Error_Codes = index++; - private static final int CD3_CD4_CD45_Lymph_Events = index++; - private static final int CD3_CD4_CD45_CD3__per_Lymph = index++; - private static final int CD3_CD4_CD45_CD3__Abs_Cnt = index++; - private static final int CD3_CD4_CD45_CD3_CD4__per_Lymph = index++; - private static final int columns = index++; - - private static final String DELIMITER = "\t"; - - private static final String DATE_PATTERN = "dd-MMMM-yy kk:mm:ss"; - private static final String ALT_DATE_PATTERN = "dd MMM yyyy KK:mm"; - private static String[] testNameIndex = new String[columns]; - private static String[] unitsIndex = new String[columns]; - - { - testNameIndex[Avg_CD3__per_Lymph] = "CD3_PER"; - testNameIndex[Avg_CD3_CD4__per_Lymph] = "CD4_PER"; - - unitsIndex[Avg_CD3__per_Lymph] = "%"; - unitsIndex[Avg_CD3_CD4__per_Lymph] = "%"; - } - - @Override - public boolean insert(List lines, String currentUserId) { - - boolean successful = true; - - List results = new ArrayList<>(); - - for (int i = 1; i < lines.size(); i++) { - addAnalyzerResultFromLine(results, lines.get(i)); + private static final String CONTROL_ACCESSION_PREFIX = "IMM"; + + private static int index = 0; + private static final int Institution = index++; + private static final int Director = index++; + private static final int Operator = index++; + private static final int Cytometer = index++; + private static final int Cytometer_Serial_Number = index++; + private static final int Software_Version = index++; + private static final int Sample_Name = index++; + private static final int Sample_ID = index++; + private static final int Case_Number = index++; + private static final int Column_1 = index++; + private static final int Column_2 = index++; + private static final int Column_3 = index++; + private static final int Panel_Name = index++; + private static final int Collection_Date = index++; + private static final int Date_Analyzed = index++; + private static final int Lab_Report_File_Name = index++; + private static final int Physicians_Report_File_Name = index++; + private static final int WBC_Count_x1000 = index++; + private static final int Lymphs_per = index++; + private static final int Lymphs_x1000 = index++; + private static final int Abs_Cnt_Bead_Name = index++; + private static final int Abs_Cnt_Bead_Lot_ID = index++; + private static final int Abs_Cnt_Beads_Pellet = index++; + private static final int Control_Bead_Name = index++; + private static final int Control_Bead_Lot_ID = index++; + private static final int Control_Low_Beads_µL = index++; + private static final int Control_Medium_Beads_µL = index++; + private static final int Control_High_Beads_µL = index++; + private static final int Control_Low_SD = index++; + private static final int Control_Medium_SD = index++; + private static final int Control_High_SD = index++; + private static final int Ref_Range = index++; + private static final int Comments = index++; + private static final int Lymphosum = index++; + private static final int CD3_per_Lymph_Difference = index++; + private static final int T_Helper_Suppressor_Ratio = index++; + private static final int Min_CD3_Abs_Cnt_Range = index++; + private static final int Max_CD3_Abs_Cnt_Range = index++; + private static final int Avg_CD3_CD4_per_T_Lymph = index++; + private static final int Avg_CD3_CD8__per_T_Lymph = index++; + private static final int Avg_CD3_CD4_CD8__per_T_Lymph = index++; + private static final int Avg_CD3__per_Lymph = index++; + private static final int Avg_CD3__Abs_Cnt = index++; + private static final int Avg_CD3_CD4__per_Lymph = index++; + private static final int Avg_CD3_CD4__Abs_Cnt = index++; + private static final int Avg_CD3_CD8__per_Lymph = index++; + private static final int Avg_CD3_CD8__Abs_Cnt = index++; + private static final int Avg_CD3_CD4_CD8__per_Lymph = index++; + private static final int Avg_CD3_CD4_CD8__Abs_Cnt = index++; + private static final int Avg_CD19__per_Lymph = index++; + private static final int Avg_CD19__Abs_Cnt = index++; + private static final int Avg_CD16_56__per_Lymph = index++; + private static final int Avg_CD16_56__Abs_Cnt = index++; + private static final int CD45__Abs_Cnt = index++; + private static final int CD3_CD4_CD45_FCS_File_Name = index++; + private static final int CD3_CD4_CD45_Lot_ID = index++; + private static final int CD3_CD4_CD45_Collection_Time = index++; + private static final int CD3_CD4_CD45_Total_Events = index++; + private static final int CD3_CD4_CD45_Tube_Name = index++; + private static final int CD3_CD4_CD45_Attr_Def_File_Name = index++; + private static final int CD3_CD4_CD45_Error_Codes = index++; + private static final int CD3_CD4_CD45_Lymph_Events = index++; + private static final int CD3_CD4_CD45_CD3__per_Lymph = index++; + private static final int CD3_CD4_CD45_CD3__Abs_Cnt = index++; + private static final int CD3_CD4_CD45_CD3_CD4__per_Lymph = index++; + private static final int columns = index++; + + private static final String DELIMITER = "\t"; + + private static final String DATE_PATTERN = "dd-MMMM-yy kk:mm:ss"; + private static final String ALT_DATE_PATTERN = "dd MMM yyyy KK:mm"; + private static String[] testNameIndex = new String[columns]; + private static String[] unitsIndex = new String[columns]; + + { + testNameIndex[Avg_CD3__per_Lymph] = "CD3_PER"; + testNameIndex[Avg_CD3_CD4__per_Lymph] = "CD4_PER"; + + unitsIndex[Avg_CD3__per_Lymph] = "%"; + unitsIndex[Avg_CD3_CD4__per_Lymph] = "%"; } - if (results.size() > 0) { + @Override + public boolean insert(List lines, String currentUserId) { - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - successful = false; - } - } + boolean successful = true; - return successful; - } + List results = new ArrayList<>(); - private void addAnalyzerResultFromLine(List results, String line) { - String[] fields = line.split(DELIMITER); + for (int i = 1; i < lines.size(); i++) { + addAnalyzerResultFromLine(results, lines.get(i)); + } - AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - String analyzerAccessionNumber = fields[Sample_ID]; + if (results.size() > 0) { - String date = fields[Collection_Date]; + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + successful = false; + } + } - for (int i = 0; i < testNameIndex.length; i++) { - if (!GenericValidator.isBlankOrNull(testNameIndex[i])) { - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.FACSCALIBUR, testNameIndex[i]); + return successful; + } - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName(AnalyzerTestNameCache.FACSCALIBUR, testNameIndex[i]); - } + private void addAnalyzerResultFromLine(List results, String line) { + String[] fields = line.split(DELIMITER); - AnalyzerResults analyzerResults = new AnalyzerResults(); + AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + String analyzerAccessionNumber = fields[Sample_ID]; - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + String date = fields[Collection_Date]; - String result = fields[i]; + for (int i = 0; i < testNameIndex.length; i++) { + if (!GenericValidator.isBlankOrNull(testNameIndex[i])) { + MappedTestName mappedName = AnalyzerTestNameCache.getInstance() + .getMappedTest(AnalyzerTestNameCache.FACSCALIBUR, testNameIndex[i]); - analyzerResults.setResult(result); - analyzerResults.setUnits(unitsIndex[i]); - String dateTime = date; - Timestamp timestamp = getTimestampFromDate(dateTime); - analyzerResults.setCompleteDate(timestamp); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setAccessionNumber(analyzerAccessionNumber); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance() + .getEmptyMappedTestName(AnalyzerTestNameCache.FACSCALIBUR, testNameIndex[i]); + } - if (analyzerAccessionNumber != null) { - analyzerResults.setIsControl( - analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); - } else { - analyzerResults.setIsControl(false); - } + AnalyzerResults analyzerResults = new AnalyzerResults(); - results.add(analyzerResults); + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); - if (resultFromDB != null) { - results.add(resultFromDB); - } - } - } - } + String result = fields[i]; + + analyzerResults.setResult(result); + analyzerResults.setUnits(unitsIndex[i]); + String dateTime = date; + Timestamp timestamp = getTimestampFromDate(dateTime); + analyzerResults.setCompleteDate(timestamp); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setAccessionNumber(analyzerAccessionNumber); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); - private Timestamp getTimestampFromDate(String dateTime) { - // Mixed date formats are sneaking in ie 24-Jul-12 15:07:09 or Mer 25 juil 2012 - // 9:46 - if (dateTime.contains("-")) { - return DateUtil.convertStringDateToTimestampWithPatternNoLocale(dateTime, DATE_PATTERN); + if (analyzerAccessionNumber != null) { + analyzerResults.setIsControl(analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); + } else { + analyzerResults.setIsControl(false); + } + + results.add(analyzerResults); + + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); + if (resultFromDB != null) { + results.add(resultFromDB); + } + } + } } - String[] dateSegs = dateTime.split(" "); - String month = getCorrectedMonth(dateSegs[2]); + private Timestamp getTimestampFromDate(String dateTime) { + // Mixed date formats are sneaking in ie 24-Jul-12 15:07:09 or Mer 25 juil 2012 + // 9:46 + if (dateTime.contains("-")) { + return DateUtil.convertStringDateToTimestampWithPatternNoLocale(dateTime, DATE_PATTERN); + } - String date = dateSegs[1] + " " + month + " " + dateSegs[3] + " " + dateSegs[4]; + String[] dateSegs = dateTime.split(" "); + String month = getCorrectedMonth(dateSegs[2]); - return DateUtil.convertStringDateToTimestampWithPattern(date, ALT_DATE_PATTERN); - } + String date = dateSegs[1] + " " + month + " " + dateSegs[3] + " " + dateSegs[4]; - // The analyzer is sending abbreviated months without the '.' - private String getCorrectedMonth(String month) { - if (month.endsWith(".") - || month.equals("mars") - || month.equals("mai") - || month.equals("juin") - || month.equals("août")) { - return month; + return DateUtil.convertStringDateToTimestampWithPattern(date, ALT_DATE_PATTERN); } - return month + "."; - } + // The analyzer is sending abbreviated months without the '.' + private String getCorrectedMonth(String month) { + if (month.endsWith(".") || month.equals("mars") || month.equals("mai") || month.equals("juin") + || month.equals("août")) { + return month; + } + + return month + "."; + } - @Override - public String getError() { - return "Facscalibur analyzer unable to write to database"; - } + @Override + public String getError() { + return "Facscalibur analyzer unable to write to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/SysmexReader.java b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/SysmexReader.java index bcf428c646..eb746c17da 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/SysmexReader.java +++ b/src/main/java/org/openelisglobal/analyzerimport/analyzerreaders/SysmexReader.java @@ -29,390 +29,385 @@ @SuppressWarnings("unused") public class SysmexReader extends AnalyzerLineInserter { - private static final String CONTROL_ACCESSION_PREFIX = "QC-"; - - private static int index = 0; - private static final int ID_INSTRUMENT = index++; - private static final int DATE = index++; - private static final int TIME = index++; - private static final int RACK = index++; - private static final int TUBE = index++; - private static final int ACCESSION = index++; - private static final int ACCESSION_INFO = index++; - private static final int METHOD = index++; - private static final int ID_PATIENT = index++; - private static final int ANALYSIS_INFO = index++; - private static final int POS_NEG = index++; - private static final int POS_DIFF = index++; - private static final int POS_MORF = index++; - private static final int POS_COMP = index++; - private static final int ERR_FUNC = index++; - private static final int ERR_RESULT = index++; - private static final int INFO_REQUEST = index++; - private static final int GB_ABNORMAL = index++; - private static final int GB_SUSPICIOUS = index++; - private static final int GR_ABNORMAL = index++; - private static final int GR_SUSPICIOUS = index++; - private static final int PLQ_ABNORMAL = index++; - private static final int PLQ_SUSPICIOUS = index++; - private static final int INFO_UNITS = index++; - private static final int INFO_PLQ = index++; - private static final int VALID = index++; - private static final int RET_MESSAGES = index++; - private static final int DELTA_MESSAGES = index++; - private static final int SAMPLE_COMMENT = index++; - private static final int PATIENT_NAME = index++; - private static final int PATIENT_BIRTH_DATE = index++; - private static final int PATIENT_GENDER = index++; - private static final int PATIENT_COMMENT = index++; - private static final int SERVICE = index++; - private static final int MEDS = index++; - private static final int TRANSMISSION_PARMS = index++; - private static final int SEQUENECE_COUNT = index++; - private static final int GB_10_uL = index++; - private static final int GB_M = index++; - private static final int GR_100000_uL = index++; - private static final int GR_M = index++; - private static final int HBG_g_L = index++; - private static final int HBG_M = index++; - private static final int HCT_10_NEG_1_PER = index++; - private static final int HCT_M = index++; - private static final int VGM_10_NEG_1_fL = index++; - private static final int VGM_M = index++; - private static final int TCMH_10_NEG_1_pg = index++; - private static final int TCMH_M = index++; - private static final int CCMH_g_L = index++; - private static final int CCMH_M = index++; - private static final int PLQ_10_3_uL = index++; - private static final int PLQ_M = index++; - private static final int IDR_SD_10_NEG_1_fL = index++; - private static final int IDR_SD_M = index++; - private static final int IDR_CV_10_NEG_1_PER = index++; - private static final int IDR_CV_M = index++; - private static final int IDP = index++; - private static final int IDP_M = index++; - private static final int VPM_10_NEG_1_fL = index++; - private static final int VPM_M = index++; - private static final int P_RGC_10_NEG_1_PER = index++; - private static final int P_RGC_M = index++; - private static final int PCT_10_NEG_2_PER = index++; - private static final int PCT_M = index++; - private static final int NEUT_COUNT_10_uL = index++; - private static final int NEUT_COUNT_M = index++; - private static final int LYMPH_COUNT_10_uL = index++; - private static final int LYMPH_COUNT_M = index++; - private static final int MONO_COUNT_10_uL = index++; - private static final int MONO_COUNT_M = index++; - private static final int EO_COUNT_10_uL = index++; - private static final int EO_COUNT_M = index++; - private static final int BASO_COUNT_10_uL = index++; - private static final int BASO_COUNT_M = index++; - private static final int NEUT_PER_10_NEG_1_PER = index++; - private static final int NEUT_PER_M = index++; - private static final int LYMPH_PER_10_NEG_1_PER = index++; - private static final int LYMPH_PER_M = index++; - private static final int MONO_PER_10_NEG_1_PER = index++; - private static final int MONO_PER_M = index++; - private static final int EO_PER_10_NEG_1_PER = index++; - private static final int EO_PER_M = index++; - private static final int BASO_PER_10_NEG_1_PER = index++; - private static final int BASO_PER_M = index++; - private static final int RET_COUNT_10_2_uL = index++; - private static final int RET_COUNT_M = index++; - private static final int RET_PER_10_NEG_2_PER = index++; - private static final int RET_PER_M = index++; - private static final int LFR_10_NEG_1_PER = index++; - private static final int LFR_M = index++; - private static final int MFR_10_NEG_1_PER = index++; - private static final int MFR_M = index++; - private static final int HFR_10_NEG_1_PER = index++; - private static final int HFR_M = index++; - private static final int IRF_10_NEG_1_PER = index++; - private static final int IRF_M = index++; - private static final int IG_COUNT_10_uL = index++; - private static final int IG_COUNT_M = index++; - private static final int IG_PER_10_NEG_1_PER = index++; - private static final int IG_PER_M = index++; - private static final int NEUT_COUNT_AND_10_uL = index++; - private static final int NEUT_COUNT_AND_M = index++; - private static final int NEUT_PER_AND_10_NEG_1_PER = index++; - private static final int NEUT_PER_AND_M = index++; - private static final int NRBC_PLUS_W_10_uL = index++; - private static final int NRBC_PLUS_W_M = index++; - private static final int LYMPH_COUNT_AND_10_uL = index++; - private static final int LYMPH_COUNT_AND_M = index++; - private static final int LYMPH_PER_AND_10_NEG_1_PER = index++; - private static final int LYMPH_PER_AND_M = index++; - private static final int OTHER_COUNT_10_uL = index++; - private static final int OTHER_COUNT_M = index++; - private static final int OTHER_PER_10_NEG_1_PER = index++; - private static final int OTHER_PER_M = index++; - private static final int GR_O_10_4_uL = index++; - private static final int GR_O_M = index++; - private static final int PLQ_O_10_3_uL = index++; - private static final int PLQ_O_M = index++; - private static final int IP_Abn_GB_Scatterg_GB_Anorm = index++; - private static final int IP_Abn_GB_NEUTROPENIA = index++; - private static final int IP_Abn_GB_NEUTROPHILIE = index++; - private static final int IP_Abn_GB_LYMPHOPENIA = index++; - private static final int IP_Abn_GB_LYMPHCYTOSIS = index++; - private static final int IP_Abn_GB_MONOCYTOSIS = index++; - private static final int IP_Abn_GB_EOSINOPHILIE = index++; - private static final int IP_Abn_GB_BASOPHILIE = index++; - private static final int IP_Abn_GB_LEUCOPENIA = index++; - private static final int IP_Abn_GB_LEUCOCYTOSIS = index++; - private static final int IP_Abn_GR_Dist_GR_An = index++; - private static final int IP_Abn_GR_D_pop_GR = index++; - private static final int IP_Abn_GR_ANISOCYTOSIS = index++; - private static final int IP_Abn_GR_MICROCYTOSIS = index++; - private static final int IP_Abn_GR_MACROCYTOSIS = index++; - private static final int IP_Abn_GR_HYPOCHROMIA = index++; - private static final int IP_Abn_GR_ANEMIA = index++; - private static final int IP_Abn_GR_ERYTHROCYTOSIS = index++; - private static final int IP_Abn_GR_Scatterg_RET_Anorm = index++; - private static final int IP_Abn_GR_RETICULOCYTOSIS = index++; - private static final int IP_Abn_PLQ_Dist_PLQ_An = index++; - private static final int IP_Abn_PLQ_THROMBOCYTOPENIA = index++; - private static final int IP_Abn_PLQ_THROMBOCYTOSIS = index++; - private static final int IP_Abn_PLQ_Scatterg_PLQ_Anorm = index++; - private static final int IP_SUS_GB_Blasts = index++; - private static final int IP_SUS_GB_Gra_Immat = index++; - private static final int IP_SUS_GB_Dev_Gauche = index++; - private static final int IP_SUS_GB_Lympho_Aty = index++; - private static final int IP_SUS_GB_Anor_Ly_Blasts = index++; - private static final int IP_SUS_GB_NRBC = index++; - private static final int IP_SUS_GB_Res_GR_Lyse = index++; - private static final int IP_SUS_GR_Agglut_GR = index++; - private static final int IP_SUS_GR_Turb_HGB_Interf = index++; - private static final int IP_SUS_GR_IRON_DEFICIENCY = index++; - private static final int IP_SUS_GR_Def_HGB = index++; - private static final int IP_SUS_GR_Fragments = index++; - private static final int IP_SUS_PLQ_Agg_PLQ = index++; - private static final int IP_SUS_PLQ_Agg_PLQ_S = index++; - private static final int DEFAULT_INFO = index++; - private static final int Qflag_Blasts = index++; - private static final int Qflag_Gra_Immat = index++; - private static final int Qflag_Dev_Gauche = index++; - private static final int Qflag_Lympho_Aty = index++; - private static final int Qflag_NRBC = index++; - private static final int Qflag_Abn_Ly_Bla = index++; - private static final int Qflag_Res_GR_Lysis = index++; - private static final int Qflag_Agglut_GR = index++; - private static final int Qflag_Turb_HGB = index++; - private static final int Qflag_IRON_DEFICIENCY = index++; - private static final int Qflag_Def_HGB = index++; - private static final int Qflag_Fragments = index++; - private static final int Qflag_Agg_PLQ = index++; - private static final int Qflag_Agg_PLQ_S = index++; - private static final int columns = index++; - - private static final String DELIMITER = ","; - - private static final String DATE_PATTERN = "dd/MM/yyyy HH:mm:ss"; - private static String[] testNameIndex = new String[columns]; - private static String[] unitsIndex = new String[columns]; - private static Boolean[] readOnlyIndex = new Boolean[columns]; - private static int[] scaleIndex = new int[columns]; - private static int[] orderedTestIndexs = new int[18]; - - { - testNameIndex[GB_10_uL] = "GB_10_uL"; - testNameIndex[GR_100000_uL] = "GR_100000_uL"; - testNameIndex[NEUT_PER_10_NEG_1_PER] = "NEUT_PER_10_NEG_1_PER"; - testNameIndex[HBG_g_L] = "HBG_g_L"; - testNameIndex[LYMPH_PER_10_NEG_1_PER] = "LYMPH_PER_10_NEG_1_PER"; - testNameIndex[HCT_10_NEG_1_PER] = "HCT_10_NEG_1_PER"; - testNameIndex[MONO_PER_10_NEG_1_PER] = "MONO_PER_10_NEG_1_PER"; - testNameIndex[VGM_10_NEG_1_fL] = "VGM_10_NEG_1_fL"; - testNameIndex[EO_PER_10_NEG_1_PER] = "EO_PER_10_NEG_1_PER"; - testNameIndex[TCMH_10_NEG_1_pg] = "TCMH_10_NEG_1_pg"; - testNameIndex[BASO_PER_10_NEG_1_PER] = "BASO_PER_10_NEG_1_PER"; - testNameIndex[CCMH_g_L] = "CCMH_g_L"; - testNameIndex[PLQ_10_3_uL] = "PLQ_10_3_uL"; - - /* - * testNameIndex[NEUT_COUNT_10_uL] = "NE#"; testNameIndex[MONO_COUNT_10_uL] = - * "MO#"; testNameIndex[BASO_COUNT_10_uL] = "BA#"; - * testNameIndex[LYMPH_COUNT_10_uL] = "LY#"; testNameIndex[EO_COUNT_10_uL] = - * "EO#"; - */ - - unitsIndex[GB_10_uL] = "10^3/ul"; - unitsIndex[GR_100000_uL] = "10^6/ul"; - unitsIndex[NEUT_PER_10_NEG_1_PER] = "%"; - unitsIndex[HBG_g_L] = "g/dl"; - unitsIndex[LYMPH_PER_10_NEG_1_PER] = "%"; - unitsIndex[HCT_10_NEG_1_PER] = "%"; - unitsIndex[MONO_PER_10_NEG_1_PER] = "%"; - unitsIndex[VGM_10_NEG_1_fL] = "fl"; - unitsIndex[EO_PER_10_NEG_1_PER] = "%"; - unitsIndex[TCMH_10_NEG_1_pg] = "pg"; - unitsIndex[BASO_PER_10_NEG_1_PER] = "%"; - unitsIndex[CCMH_g_L] = "g/l"; - unitsIndex[PLQ_10_3_uL] = "10^3/ul"; - - /* - * unitsIndex[NEUT_COUNT_10_uL] = " "; unitsIndex[MONO_COUNT_10_uL] = " "; - * unitsIndex[BASO_COUNT_10_uL] = " "; unitsIndex[LYMPH_COUNT_10_uL] = " "; - * unitsIndex[EO_COUNT_10_uL] = " "; - */ - for (int i = 0; i < readOnlyIndex.length; i++) { - readOnlyIndex[i] = Boolean.FALSE; - } - - /* - * readOnlyIndex[NEUT_COUNT_10_uL] = Boolean.TRUE; - * readOnlyIndex[MONO_COUNT_10_uL] = Boolean.TRUE; - * readOnlyIndex[BASO_COUNT_10_uL] = Boolean.TRUE; - * readOnlyIndex[LYMPH_COUNT_10_uL] = Boolean.TRUE; - * readOnlyIndex[EO_COUNT_10_uL] = Boolean.TRUE; - */ - scaleIndex[GB_10_uL] = 100; - scaleIndex[GR_100000_uL] = 100; - scaleIndex[NEUT_PER_10_NEG_1_PER] = 10; - scaleIndex[HBG_g_L] = 10; - scaleIndex[LYMPH_PER_10_NEG_1_PER] = 10; - scaleIndex[HCT_10_NEG_1_PER] = 10; - scaleIndex[MONO_PER_10_NEG_1_PER] = 10; - scaleIndex[VGM_10_NEG_1_fL] = 10; - scaleIndex[EO_PER_10_NEG_1_PER] = 10; - scaleIndex[TCMH_10_NEG_1_pg] = 10; - scaleIndex[BASO_PER_10_NEG_1_PER] = 10; - scaleIndex[CCMH_g_L] = 10; - scaleIndex[PLQ_10_3_uL] = 1; - /* - * scaleIndex[NEUT_COUNT_10_uL] = 100; scaleIndex[MONO_COUNT_10_uL] = 100; - * scaleIndex[BASO_COUNT_10_uL] = 10; scaleIndex[LYMPH_COUNT_10_uL] = 100; - * scaleIndex[EO_COUNT_10_uL] = 100; - */ - - orderedTestIndexs[0] = GB_10_uL; - orderedTestIndexs[6] = GR_100000_uL; - orderedTestIndexs[1] = NEUT_PER_10_NEG_1_PER; - orderedTestIndexs[7] = HBG_g_L; - orderedTestIndexs[2] = LYMPH_PER_10_NEG_1_PER; - orderedTestIndexs[8] = HCT_10_NEG_1_PER; - orderedTestIndexs[3] = MONO_PER_10_NEG_1_PER; - orderedTestIndexs[9] = VGM_10_NEG_1_fL; - orderedTestIndexs[4] = EO_PER_10_NEG_1_PER; - orderedTestIndexs[10] = TCMH_10_NEG_1_pg; - orderedTestIndexs[5] = BASO_PER_10_NEG_1_PER; - orderedTestIndexs[11] = CCMH_g_L; - orderedTestIndexs[12] = PLQ_10_3_uL; - - orderedTestIndexs[13] = NEUT_COUNT_10_uL; - orderedTestIndexs[15] = MONO_COUNT_10_uL; - orderedTestIndexs[17] = BASO_COUNT_10_uL; - orderedTestIndexs[14] = LYMPH_COUNT_10_uL; - orderedTestIndexs[16] = EO_COUNT_10_uL; - - /* - * GB_10_uL WBC 100 GR_100000_uL RBC 100 NEUT_PER_10_NEG_1_PER NE% 10 HBG_g_L - * HGB 10 LYMPH_PER_10_NEG_1_PER LY% 10 HCT_10_NEG_1_PER HCT 10 - * MONO_PER_10_NEG_1_PER MO% 10 VGM_10_NEG_1_fL MVC 10 EO_PER_10_NEG_1_PER EO% - * 10 TCMH_10_NEG_1_pg MCH 10 BASO_PER_10_NEG_1_PER BA% 10 CCMH_g_L MCHC 10 - * PLQ_10_3_uL PLT 1 - * - * NEUT_COUNT_10_uL NE# 100 MONO_COUNT_10_uL MO# 100 BASO_COUNT_10_uL BA# 10 - * LYMPH_COUNT_10_uL LY# 100 EO_COUNT_10_uL EO# 100 - */ - } - - @Override - public boolean insert(List lines, String currentUserId) { - - boolean successful = true; - - List results = new ArrayList<>(); - - for (int i = 1; i < lines.size(); i++) { - addAnalyzerResultFromLine(results, lines.get(i)); - } + private static final String CONTROL_ACCESSION_PREFIX = "QC-"; + + private static int index = 0; + private static final int ID_INSTRUMENT = index++; + private static final int DATE = index++; + private static final int TIME = index++; + private static final int RACK = index++; + private static final int TUBE = index++; + private static final int ACCESSION = index++; + private static final int ACCESSION_INFO = index++; + private static final int METHOD = index++; + private static final int ID_PATIENT = index++; + private static final int ANALYSIS_INFO = index++; + private static final int POS_NEG = index++; + private static final int POS_DIFF = index++; + private static final int POS_MORF = index++; + private static final int POS_COMP = index++; + private static final int ERR_FUNC = index++; + private static final int ERR_RESULT = index++; + private static final int INFO_REQUEST = index++; + private static final int GB_ABNORMAL = index++; + private static final int GB_SUSPICIOUS = index++; + private static final int GR_ABNORMAL = index++; + private static final int GR_SUSPICIOUS = index++; + private static final int PLQ_ABNORMAL = index++; + private static final int PLQ_SUSPICIOUS = index++; + private static final int INFO_UNITS = index++; + private static final int INFO_PLQ = index++; + private static final int VALID = index++; + private static final int RET_MESSAGES = index++; + private static final int DELTA_MESSAGES = index++; + private static final int SAMPLE_COMMENT = index++; + private static final int PATIENT_NAME = index++; + private static final int PATIENT_BIRTH_DATE = index++; + private static final int PATIENT_GENDER = index++; + private static final int PATIENT_COMMENT = index++; + private static final int SERVICE = index++; + private static final int MEDS = index++; + private static final int TRANSMISSION_PARMS = index++; + private static final int SEQUENECE_COUNT = index++; + private static final int GB_10_uL = index++; + private static final int GB_M = index++; + private static final int GR_100000_uL = index++; + private static final int GR_M = index++; + private static final int HBG_g_L = index++; + private static final int HBG_M = index++; + private static final int HCT_10_NEG_1_PER = index++; + private static final int HCT_M = index++; + private static final int VGM_10_NEG_1_fL = index++; + private static final int VGM_M = index++; + private static final int TCMH_10_NEG_1_pg = index++; + private static final int TCMH_M = index++; + private static final int CCMH_g_L = index++; + private static final int CCMH_M = index++; + private static final int PLQ_10_3_uL = index++; + private static final int PLQ_M = index++; + private static final int IDR_SD_10_NEG_1_fL = index++; + private static final int IDR_SD_M = index++; + private static final int IDR_CV_10_NEG_1_PER = index++; + private static final int IDR_CV_M = index++; + private static final int IDP = index++; + private static final int IDP_M = index++; + private static final int VPM_10_NEG_1_fL = index++; + private static final int VPM_M = index++; + private static final int P_RGC_10_NEG_1_PER = index++; + private static final int P_RGC_M = index++; + private static final int PCT_10_NEG_2_PER = index++; + private static final int PCT_M = index++; + private static final int NEUT_COUNT_10_uL = index++; + private static final int NEUT_COUNT_M = index++; + private static final int LYMPH_COUNT_10_uL = index++; + private static final int LYMPH_COUNT_M = index++; + private static final int MONO_COUNT_10_uL = index++; + private static final int MONO_COUNT_M = index++; + private static final int EO_COUNT_10_uL = index++; + private static final int EO_COUNT_M = index++; + private static final int BASO_COUNT_10_uL = index++; + private static final int BASO_COUNT_M = index++; + private static final int NEUT_PER_10_NEG_1_PER = index++; + private static final int NEUT_PER_M = index++; + private static final int LYMPH_PER_10_NEG_1_PER = index++; + private static final int LYMPH_PER_M = index++; + private static final int MONO_PER_10_NEG_1_PER = index++; + private static final int MONO_PER_M = index++; + private static final int EO_PER_10_NEG_1_PER = index++; + private static final int EO_PER_M = index++; + private static final int BASO_PER_10_NEG_1_PER = index++; + private static final int BASO_PER_M = index++; + private static final int RET_COUNT_10_2_uL = index++; + private static final int RET_COUNT_M = index++; + private static final int RET_PER_10_NEG_2_PER = index++; + private static final int RET_PER_M = index++; + private static final int LFR_10_NEG_1_PER = index++; + private static final int LFR_M = index++; + private static final int MFR_10_NEG_1_PER = index++; + private static final int MFR_M = index++; + private static final int HFR_10_NEG_1_PER = index++; + private static final int HFR_M = index++; + private static final int IRF_10_NEG_1_PER = index++; + private static final int IRF_M = index++; + private static final int IG_COUNT_10_uL = index++; + private static final int IG_COUNT_M = index++; + private static final int IG_PER_10_NEG_1_PER = index++; + private static final int IG_PER_M = index++; + private static final int NEUT_COUNT_AND_10_uL = index++; + private static final int NEUT_COUNT_AND_M = index++; + private static final int NEUT_PER_AND_10_NEG_1_PER = index++; + private static final int NEUT_PER_AND_M = index++; + private static final int NRBC_PLUS_W_10_uL = index++; + private static final int NRBC_PLUS_W_M = index++; + private static final int LYMPH_COUNT_AND_10_uL = index++; + private static final int LYMPH_COUNT_AND_M = index++; + private static final int LYMPH_PER_AND_10_NEG_1_PER = index++; + private static final int LYMPH_PER_AND_M = index++; + private static final int OTHER_COUNT_10_uL = index++; + private static final int OTHER_COUNT_M = index++; + private static final int OTHER_PER_10_NEG_1_PER = index++; + private static final int OTHER_PER_M = index++; + private static final int GR_O_10_4_uL = index++; + private static final int GR_O_M = index++; + private static final int PLQ_O_10_3_uL = index++; + private static final int PLQ_O_M = index++; + private static final int IP_Abn_GB_Scatterg_GB_Anorm = index++; + private static final int IP_Abn_GB_NEUTROPENIA = index++; + private static final int IP_Abn_GB_NEUTROPHILIE = index++; + private static final int IP_Abn_GB_LYMPHOPENIA = index++; + private static final int IP_Abn_GB_LYMPHCYTOSIS = index++; + private static final int IP_Abn_GB_MONOCYTOSIS = index++; + private static final int IP_Abn_GB_EOSINOPHILIE = index++; + private static final int IP_Abn_GB_BASOPHILIE = index++; + private static final int IP_Abn_GB_LEUCOPENIA = index++; + private static final int IP_Abn_GB_LEUCOCYTOSIS = index++; + private static final int IP_Abn_GR_Dist_GR_An = index++; + private static final int IP_Abn_GR_D_pop_GR = index++; + private static final int IP_Abn_GR_ANISOCYTOSIS = index++; + private static final int IP_Abn_GR_MICROCYTOSIS = index++; + private static final int IP_Abn_GR_MACROCYTOSIS = index++; + private static final int IP_Abn_GR_HYPOCHROMIA = index++; + private static final int IP_Abn_GR_ANEMIA = index++; + private static final int IP_Abn_GR_ERYTHROCYTOSIS = index++; + private static final int IP_Abn_GR_Scatterg_RET_Anorm = index++; + private static final int IP_Abn_GR_RETICULOCYTOSIS = index++; + private static final int IP_Abn_PLQ_Dist_PLQ_An = index++; + private static final int IP_Abn_PLQ_THROMBOCYTOPENIA = index++; + private static final int IP_Abn_PLQ_THROMBOCYTOSIS = index++; + private static final int IP_Abn_PLQ_Scatterg_PLQ_Anorm = index++; + private static final int IP_SUS_GB_Blasts = index++; + private static final int IP_SUS_GB_Gra_Immat = index++; + private static final int IP_SUS_GB_Dev_Gauche = index++; + private static final int IP_SUS_GB_Lympho_Aty = index++; + private static final int IP_SUS_GB_Anor_Ly_Blasts = index++; + private static final int IP_SUS_GB_NRBC = index++; + private static final int IP_SUS_GB_Res_GR_Lyse = index++; + private static final int IP_SUS_GR_Agglut_GR = index++; + private static final int IP_SUS_GR_Turb_HGB_Interf = index++; + private static final int IP_SUS_GR_IRON_DEFICIENCY = index++; + private static final int IP_SUS_GR_Def_HGB = index++; + private static final int IP_SUS_GR_Fragments = index++; + private static final int IP_SUS_PLQ_Agg_PLQ = index++; + private static final int IP_SUS_PLQ_Agg_PLQ_S = index++; + private static final int DEFAULT_INFO = index++; + private static final int Qflag_Blasts = index++; + private static final int Qflag_Gra_Immat = index++; + private static final int Qflag_Dev_Gauche = index++; + private static final int Qflag_Lympho_Aty = index++; + private static final int Qflag_NRBC = index++; + private static final int Qflag_Abn_Ly_Bla = index++; + private static final int Qflag_Res_GR_Lysis = index++; + private static final int Qflag_Agglut_GR = index++; + private static final int Qflag_Turb_HGB = index++; + private static final int Qflag_IRON_DEFICIENCY = index++; + private static final int Qflag_Def_HGB = index++; + private static final int Qflag_Fragments = index++; + private static final int Qflag_Agg_PLQ = index++; + private static final int Qflag_Agg_PLQ_S = index++; + private static final int columns = index++; + + private static final String DELIMITER = ","; + + private static final String DATE_PATTERN = "dd/MM/yyyy HH:mm:ss"; + private static String[] testNameIndex = new String[columns]; + private static String[] unitsIndex = new String[columns]; + private static Boolean[] readOnlyIndex = new Boolean[columns]; + private static int[] scaleIndex = new int[columns]; + private static int[] orderedTestIndexs = new int[18]; + + { + testNameIndex[GB_10_uL] = "GB_10_uL"; + testNameIndex[GR_100000_uL] = "GR_100000_uL"; + testNameIndex[NEUT_PER_10_NEG_1_PER] = "NEUT_PER_10_NEG_1_PER"; + testNameIndex[HBG_g_L] = "HBG_g_L"; + testNameIndex[LYMPH_PER_10_NEG_1_PER] = "LYMPH_PER_10_NEG_1_PER"; + testNameIndex[HCT_10_NEG_1_PER] = "HCT_10_NEG_1_PER"; + testNameIndex[MONO_PER_10_NEG_1_PER] = "MONO_PER_10_NEG_1_PER"; + testNameIndex[VGM_10_NEG_1_fL] = "VGM_10_NEG_1_fL"; + testNameIndex[EO_PER_10_NEG_1_PER] = "EO_PER_10_NEG_1_PER"; + testNameIndex[TCMH_10_NEG_1_pg] = "TCMH_10_NEG_1_pg"; + testNameIndex[BASO_PER_10_NEG_1_PER] = "BASO_PER_10_NEG_1_PER"; + testNameIndex[CCMH_g_L] = "CCMH_g_L"; + testNameIndex[PLQ_10_3_uL] = "PLQ_10_3_uL"; + + /* + * testNameIndex[NEUT_COUNT_10_uL] = "NE#"; testNameIndex[MONO_COUNT_10_uL] = + * "MO#"; testNameIndex[BASO_COUNT_10_uL] = "BA#"; + * testNameIndex[LYMPH_COUNT_10_uL] = "LY#"; testNameIndex[EO_COUNT_10_uL] = + * "EO#"; + */ + + unitsIndex[GB_10_uL] = "10^3/ul"; + unitsIndex[GR_100000_uL] = "10^6/ul"; + unitsIndex[NEUT_PER_10_NEG_1_PER] = "%"; + unitsIndex[HBG_g_L] = "g/dl"; + unitsIndex[LYMPH_PER_10_NEG_1_PER] = "%"; + unitsIndex[HCT_10_NEG_1_PER] = "%"; + unitsIndex[MONO_PER_10_NEG_1_PER] = "%"; + unitsIndex[VGM_10_NEG_1_fL] = "fl"; + unitsIndex[EO_PER_10_NEG_1_PER] = "%"; + unitsIndex[TCMH_10_NEG_1_pg] = "pg"; + unitsIndex[BASO_PER_10_NEG_1_PER] = "%"; + unitsIndex[CCMH_g_L] = "g/l"; + unitsIndex[PLQ_10_3_uL] = "10^3/ul"; + + /* + * unitsIndex[NEUT_COUNT_10_uL] = " "; unitsIndex[MONO_COUNT_10_uL] = " "; + * unitsIndex[BASO_COUNT_10_uL] = " "; unitsIndex[LYMPH_COUNT_10_uL] = " "; + * unitsIndex[EO_COUNT_10_uL] = " "; + */ + for (int i = 0; i < readOnlyIndex.length; i++) { + readOnlyIndex[i] = Boolean.FALSE; + } - if (results.size() > 0) { - try { - persistResults(results, currentUserId); - } catch (LIMSRuntimeException e) { - successful = false; - } + /* + * readOnlyIndex[NEUT_COUNT_10_uL] = Boolean.TRUE; + * readOnlyIndex[MONO_COUNT_10_uL] = Boolean.TRUE; + * readOnlyIndex[BASO_COUNT_10_uL] = Boolean.TRUE; + * readOnlyIndex[LYMPH_COUNT_10_uL] = Boolean.TRUE; + * readOnlyIndex[EO_COUNT_10_uL] = Boolean.TRUE; + */ + scaleIndex[GB_10_uL] = 100; + scaleIndex[GR_100000_uL] = 100; + scaleIndex[NEUT_PER_10_NEG_1_PER] = 10; + scaleIndex[HBG_g_L] = 10; + scaleIndex[LYMPH_PER_10_NEG_1_PER] = 10; + scaleIndex[HCT_10_NEG_1_PER] = 10; + scaleIndex[MONO_PER_10_NEG_1_PER] = 10; + scaleIndex[VGM_10_NEG_1_fL] = 10; + scaleIndex[EO_PER_10_NEG_1_PER] = 10; + scaleIndex[TCMH_10_NEG_1_pg] = 10; + scaleIndex[BASO_PER_10_NEG_1_PER] = 10; + scaleIndex[CCMH_g_L] = 10; + scaleIndex[PLQ_10_3_uL] = 1; + /* + * scaleIndex[NEUT_COUNT_10_uL] = 100; scaleIndex[MONO_COUNT_10_uL] = 100; + * scaleIndex[BASO_COUNT_10_uL] = 10; scaleIndex[LYMPH_COUNT_10_uL] = 100; + * scaleIndex[EO_COUNT_10_uL] = 100; + */ + + orderedTestIndexs[0] = GB_10_uL; + orderedTestIndexs[6] = GR_100000_uL; + orderedTestIndexs[1] = NEUT_PER_10_NEG_1_PER; + orderedTestIndexs[7] = HBG_g_L; + orderedTestIndexs[2] = LYMPH_PER_10_NEG_1_PER; + orderedTestIndexs[8] = HCT_10_NEG_1_PER; + orderedTestIndexs[3] = MONO_PER_10_NEG_1_PER; + orderedTestIndexs[9] = VGM_10_NEG_1_fL; + orderedTestIndexs[4] = EO_PER_10_NEG_1_PER; + orderedTestIndexs[10] = TCMH_10_NEG_1_pg; + orderedTestIndexs[5] = BASO_PER_10_NEG_1_PER; + orderedTestIndexs[11] = CCMH_g_L; + orderedTestIndexs[12] = PLQ_10_3_uL; + + orderedTestIndexs[13] = NEUT_COUNT_10_uL; + orderedTestIndexs[15] = MONO_COUNT_10_uL; + orderedTestIndexs[17] = BASO_COUNT_10_uL; + orderedTestIndexs[14] = LYMPH_COUNT_10_uL; + orderedTestIndexs[16] = EO_COUNT_10_uL; + + /* + * GB_10_uL WBC 100 GR_100000_uL RBC 100 NEUT_PER_10_NEG_1_PER NE% 10 HBG_g_L + * HGB 10 LYMPH_PER_10_NEG_1_PER LY% 10 HCT_10_NEG_1_PER HCT 10 + * MONO_PER_10_NEG_1_PER MO% 10 VGM_10_NEG_1_fL MVC 10 EO_PER_10_NEG_1_PER EO% + * 10 TCMH_10_NEG_1_pg MCH 10 BASO_PER_10_NEG_1_PER BA% 10 CCMH_g_L MCHC 10 + * PLQ_10_3_uL PLT 1 + * + * NEUT_COUNT_10_uL NE# 100 MONO_COUNT_10_uL MO# 100 BASO_COUNT_10_uL BA# 10 + * LYMPH_COUNT_10_uL LY# 100 EO_COUNT_10_uL EO# 100 + */ } - return successful; - } + @Override + public boolean insert(List lines, String currentUserId) { - private void addAnalyzerResultFromLine(List results, String line) { - String[] fields = line.split(DELIMITER); + boolean successful = true; - AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); - String analyzerAccessionNumber = fields[ACCESSION]; - Timestamp timestamp = - DateUtil.convertStringDateToTimestampWithPattern( - fields[DATE] + " " + fields[TIME], DATE_PATTERN); + List results = new ArrayList<>(); - List readOnlyResults = new ArrayList<>(); - - // the reason for the indirection is to get the order of tests correct - for (int i = 0; i < orderedTestIndexs.length; i++) { - int testIndex = orderedTestIndexs[i]; - - if (!GenericValidator.isBlankOrNull(testNameIndex[testIndex])) { - MappedTestName mappedName = - AnalyzerTestNameCache.getInstance() - .getMappedTest(AnalyzerTestNameCache.SYSMEX_XT2000_NAME, testNameIndex[testIndex]); - - if (mappedName == null) { - mappedName = - AnalyzerTestNameCache.getInstance() - .getEmptyMappedTestName( - AnalyzerTestNameCache.SYSMEX_XT2000_NAME, testNameIndex[testIndex]); + for (int i = 1; i < lines.size(); i++) { + addAnalyzerResultFromLine(results, lines.get(i)); } - AnalyzerResults analyzerResults = new AnalyzerResults(); - - analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); - - double result = Double.NaN; - - try { - result = Double.parseDouble(fields[testIndex]) / scaleIndex[testIndex]; - } catch (NumberFormatException e) { - LogEvent.logError(e.getMessage(), e); - // no-op -- defaults to NAN + if (results.size() > 0) { + try { + persistResults(results, currentUserId); + } catch (LIMSRuntimeException e) { + successful = false; + } } - analyzerResults.setResult(String.valueOf(result)); - analyzerResults.setUnits(unitsIndex[testIndex]); - analyzerResults.setCompleteDate(timestamp); - analyzerResults.setTestId(mappedName.getTestId()); - analyzerResults.setAccessionNumber(analyzerAccessionNumber); - analyzerResults.setTestName(mappedName.getOpenElisTestName()); - analyzerResults.setReadOnly(readOnlyIndex[testIndex]); - - if (analyzerAccessionNumber != null) { - analyzerResults.setIsControl( - analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); - } else { - analyzerResults.setIsControl(false); - } + return successful; + } - if (analyzerResults.isReadOnly()) { - readOnlyResults.add(analyzerResults); - } else { - results.add(analyzerResults); + private void addAnalyzerResultFromLine(List results, String line) { + String[] fields = line.split(DELIMITER); + + AnalyzerReaderUtil readerUtil = new AnalyzerReaderUtil(); + String analyzerAccessionNumber = fields[ACCESSION]; + Timestamp timestamp = DateUtil.convertStringDateToTimestampWithPattern(fields[DATE] + " " + fields[TIME], + DATE_PATTERN); + + List readOnlyResults = new ArrayList<>(); + + // the reason for the indirection is to get the order of tests correct + for (int i = 0; i < orderedTestIndexs.length; i++) { + int testIndex = orderedTestIndexs[i]; + + if (!GenericValidator.isBlankOrNull(testNameIndex[testIndex])) { + MappedTestName mappedName = AnalyzerTestNameCache.getInstance() + .getMappedTest(AnalyzerTestNameCache.SYSMEX_XT2000_NAME, testNameIndex[testIndex]); + + if (mappedName == null) { + mappedName = AnalyzerTestNameCache.getInstance() + .getEmptyMappedTestName(AnalyzerTestNameCache.SYSMEX_XT2000_NAME, testNameIndex[testIndex]); + } + + AnalyzerResults analyzerResults = new AnalyzerResults(); + + analyzerResults.setAnalyzerId(mappedName.getAnalyzerId()); + + double result = Double.NaN; + + try { + result = Double.parseDouble(fields[testIndex]) / scaleIndex[testIndex]; + } catch (NumberFormatException e) { + LogEvent.logError(e.getMessage(), e); + // no-op -- defaults to NAN + } + + analyzerResults.setResult(String.valueOf(result)); + analyzerResults.setUnits(unitsIndex[testIndex]); + analyzerResults.setCompleteDate(timestamp); + analyzerResults.setTestId(mappedName.getTestId()); + analyzerResults.setAccessionNumber(analyzerAccessionNumber); + analyzerResults.setTestName(mappedName.getOpenElisTestName()); + analyzerResults.setReadOnly(readOnlyIndex[testIndex]); + + if (analyzerAccessionNumber != null) { + analyzerResults.setIsControl(analyzerAccessionNumber.startsWith(CONTROL_ACCESSION_PREFIX)); + } else { + analyzerResults.setIsControl(false); + } + + if (analyzerResults.isReadOnly()) { + readOnlyResults.add(analyzerResults); + } else { + results.add(analyzerResults); + } + + AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); + if (resultFromDB != null) { + results.add(resultFromDB); + } + } } - AnalyzerResults resultFromDB = readerUtil.createAnalyzerResultFromDB(analyzerResults); - if (resultFromDB != null) { - results.add(resultFromDB); - } - } + results.addAll(readOnlyResults); } - results.addAll(readOnlyResults); - } - - @Override - public String getError() { - return "Sysmex analyzer unable to write to database"; - } + @Override + public String getError() { + return "Sysmex analyzer unable to write to database"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameController.java b/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameController.java index 4ac00fc867..325e10eac6 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameController.java +++ b/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameController.java @@ -35,214 +35,210 @@ @SessionAttributes("form") public class AnalyzerTestNameController extends BaseController { - private static final String[] ALLOWED_FIELDS = - new String[] {"analyzerId", "analyzerTestName", "testId"}; - - @Autowired private AnalyzerTestMappingValidator analyzerTestMappingValidator; - @Autowired private AnalyzerTestMappingService analyzerTestMappingService; - @Autowired private AnalyzerService analyzerService; - @Autowired private TestService testService; - - @ModelAttribute("form") - public AnalyzerTestNameForm initForm() { - return new AnalyzerTestNameForm(); - } - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setAllowedFields(ALLOWED_FIELDS); - } - - @RequestMapping(value = "/AnalyzerTestName", method = RequestMethod.GET) - public ModelAndView showAnalyzerTestName( - HttpServletRequest request, - @ModelAttribute("form") BaseForm oldForm, - RedirectAttributes redirectAttributes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - AnalyzerTestNameForm newForm = resetSessionFormToType(oldForm, AnalyzerTestNameForm.class); - newForm.setCancelAction("CancelAnalyzerTestName"); - - request.setAttribute(ALLOW_EDITS_KEY, "true"); - request.setAttribute(PREVIOUS_DISABLED, "true"); - request.setAttribute(NEXT_DISABLED, "true"); - - List analyzerList = getAllAnalyzers(); - List testList = getAllTests(); - - newForm.setAnalyzerList(analyzerList); - newForm.setTestList(testList); - - if (request.getParameter("ID") != null && isValidID(request.getParameter("ID"))) { - String[] splitId = request.getParameter("ID").split("#"); - newForm.setAnalyzerTestName(splitId[1]); - newForm.setTestId(splitId[2]); - newForm.setAnalyzerId(splitId[0]); + private static final String[] ALLOWED_FIELDS = new String[] { "analyzerId", "analyzerTestName", "testId" }; + + @Autowired + private AnalyzerTestMappingValidator analyzerTestMappingValidator; + @Autowired + private AnalyzerTestMappingService analyzerTestMappingService; + @Autowired + private AnalyzerService analyzerService; + @Autowired + private TestService testService; + + @ModelAttribute("form") + public AnalyzerTestNameForm initForm() { + return new AnalyzerTestNameForm(); } - if (org.apache.commons.validator.GenericValidator.isBlankOrNull(newForm.getAnalyzerId())) { - newForm.setNewMapping(true); - } else { - newForm.setNewMapping(false); + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); } - return findForward(FWD_SUCCESS, newForm); - } - - private boolean isValidID(String ID) { - return ID.matches("^[0-9]+#[^#/\\<>?]*#[0-9]+"); - } - - private List getAllAnalyzers() { - return analyzerService.getAll(); - } - - private List getAllTests() { - return testService.getAllActiveTests(false); - } - - @RequestMapping(value = "/AnalyzerTestName", method = RequestMethod.POST) - public ModelAndView showUpdateAnalyzerTestName( - HttpServletRequest request, - @ModelAttribute("form") @Valid AnalyzerTestNameForm form, - BindingResult result, - SessionStatus status, - RedirectAttributes redirectAttributes) { - if (result.hasErrors()) { - saveErrors(result); - return findForward(FWD_FAIL_INSERT, form); + @RequestMapping(value = "/AnalyzerTestName", method = RequestMethod.GET) + public ModelAndView showAnalyzerTestName(HttpServletRequest request, @ModelAttribute("form") BaseForm oldForm, + RedirectAttributes redirectAttributes) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + AnalyzerTestNameForm newForm = resetSessionFormToType(oldForm, AnalyzerTestNameForm.class); + newForm.setCancelAction("CancelAnalyzerTestName"); + + request.setAttribute(ALLOW_EDITS_KEY, "true"); + request.setAttribute(PREVIOUS_DISABLED, "true"); + request.setAttribute(NEXT_DISABLED, "true"); + + List analyzerList = getAllAnalyzers(); + List testList = getAllTests(); + + newForm.setAnalyzerList(analyzerList); + newForm.setTestList(testList); + + if (request.getParameter("ID") != null && isValidID(request.getParameter("ID"))) { + String[] splitId = request.getParameter("ID").split("#"); + newForm.setAnalyzerTestName(splitId[1]); + newForm.setTestId(splitId[2]); + newForm.setAnalyzerId(splitId[0]); + } + + if (org.apache.commons.validator.GenericValidator.isBlankOrNull(newForm.getAnalyzerId())) { + newForm.setNewMapping(true); + } else { + newForm.setNewMapping(false); + } + + return findForward(FWD_SUCCESS, newForm); } - String forward; + private boolean isValidID(String ID) { + return ID.matches("^[0-9]+#[^#/\\<>?]*#[0-9]+"); + } - request.setAttribute(ALLOW_EDITS_KEY, "true"); - request.setAttribute(PREVIOUS_DISABLED, "false"); - request.setAttribute(NEXT_DISABLED, "false"); + private List getAllAnalyzers() { + return analyzerService.getAll(); + } - forward = updateAnalyzerTestName(request, form, result); - if (FWD_SUCCESS_INSERT.equals(forward)) { - status.setComplete(); - redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); - return findForward(forward, form); + private List getAllTests() { + return testService.getAllActiveTests(false); } - return findForward(forward, form); - } - - public String updateAnalyzerTestName( - HttpServletRequest request, AnalyzerTestNameForm form, Errors errors) { - String forward = FWD_SUCCESS_INSERT; - String analyzerId = form.getAnalyzerId(); - String analyzerTestName = form.getAnalyzerTestName(); - String testId = form.getTestId(); - boolean newMapping = form.isNewMapping(); - - AnalyzerTestMapping analyzerTestNameMapping; - if (newMapping) { - analyzerTestNameMapping = new AnalyzerTestMapping(); - analyzerTestNameMapping.setAnalyzerId(analyzerId); - analyzerTestNameMapping.setAnalyzerTestName(analyzerTestName); - analyzerTestNameMapping.setTestId(testId); - analyzerTestNameMapping.setSysUserId(getSysUserId(request)); - } else { - analyzerTestNameMapping = getAnalyzerAndTestName(analyzerId, analyzerTestName, testId); + + @RequestMapping(value = "/AnalyzerTestName", method = RequestMethod.POST) + public ModelAndView showUpdateAnalyzerTestName(HttpServletRequest request, + @ModelAttribute("form") @Valid AnalyzerTestNameForm form, BindingResult result, SessionStatus status, + RedirectAttributes redirectAttributes) { + if (result.hasErrors()) { + saveErrors(result); + return findForward(FWD_FAIL_INSERT, form); + } + + String forward; + + request.setAttribute(ALLOW_EDITS_KEY, "true"); + request.setAttribute(PREVIOUS_DISABLED, "false"); + request.setAttribute(NEXT_DISABLED, "false"); + + forward = updateAnalyzerTestName(request, form, result); + if (FWD_SUCCESS_INSERT.equals(forward)) { + status.setComplete(); + redirectAttributes.addFlashAttribute(FWD_SUCCESS, true); + return findForward(forward, form); + } + return findForward(forward, form); } - try { - if (newMapping) { - analyzerTestMappingValidator.preInsertValidate(analyzerTestNameMapping, errors); - if (errors.hasErrors()) { - saveErrors(errors); - return FWD_FAIL_INSERT; + public String updateAnalyzerTestName(HttpServletRequest request, AnalyzerTestNameForm form, Errors errors) { + String forward = FWD_SUCCESS_INSERT; + String analyzerId = form.getAnalyzerId(); + String analyzerTestName = form.getAnalyzerTestName(); + String testId = form.getTestId(); + boolean newMapping = form.isNewMapping(); + + AnalyzerTestMapping analyzerTestNameMapping; + if (newMapping) { + analyzerTestNameMapping = new AnalyzerTestMapping(); + analyzerTestNameMapping.setAnalyzerId(analyzerId); + analyzerTestNameMapping.setAnalyzerTestName(analyzerTestName); + analyzerTestNameMapping.setTestId(testId); + analyzerTestNameMapping.setSysUserId(getSysUserId(request)); + } else { + analyzerTestNameMapping = getAnalyzerAndTestName(analyzerId, analyzerTestName, testId); + } + + try { + if (newMapping) { + analyzerTestMappingValidator.preInsertValidate(analyzerTestNameMapping, errors); + if (errors.hasErrors()) { + saveErrors(errors); + return FWD_FAIL_INSERT; + } + analyzerTestMappingService.insert(analyzerTestNameMapping); + } else { + analyzerTestMappingValidator.preUpdateValidate(analyzerTestNameMapping, errors); + if (errors.hasErrors()) { + saveErrors(errors); + return FWD_FAIL_INSERT; + } + analyzerTestNameMapping.setSysUserId(getSysUserId(request)); + analyzerTestMappingService.update(analyzerTestNameMapping); + } + + } catch (LIMSRuntimeException e) { + String errorMsg = null; + if (e.getCause() instanceof org.hibernate.StaleObjectStateException) { + errorMsg = "errors.OptimisticLockException"; + } else { + errorMsg = "errors.UpdateException"; + } + + persistError(request, errorMsg); + + disableNavigationButtons(request); + forward = FWD_FAIL_INSERT; } - analyzerTestMappingService.insert(analyzerTestNameMapping); - } else { - analyzerTestMappingValidator.preUpdateValidate(analyzerTestNameMapping, errors); - if (errors.hasErrors()) { - saveErrors(errors); - return FWD_FAIL_INSERT; + + AnalyzerTestNameCache.getInstance().reloadCache(); + + return forward; + } + + private AnalyzerTestMapping getAnalyzerAndTestName(String analyzerId, String analyzerTestName, String testId) { + + AnalyzerTestMapping existingMapping = null; + List testMappingList = analyzerTestMappingService.getAll(); + for (AnalyzerTestMapping testMapping : testMappingList) { + if (analyzerId.equals(testMapping.getAnalyzerId()) + && analyzerTestName.equals(testMapping.getAnalyzerTestName())) { + existingMapping = testMapping; + testMapping.setTestId(testId); + break; + } } - analyzerTestNameMapping.setSysUserId(getSysUserId(request)); - analyzerTestMappingService.update(analyzerTestNameMapping); - } - - } catch (LIMSRuntimeException e) { - String errorMsg = null; - if (e.getCause() instanceof org.hibernate.StaleObjectStateException) { - errorMsg = "errors.OptimisticLockException"; - } else { - errorMsg = "errors.UpdateException"; - } - - persistError(request, errorMsg); - - disableNavigationButtons(request); - forward = FWD_FAIL_INSERT; + + return existingMapping; } - AnalyzerTestNameCache.getInstance().reloadCache(); + private void persistError(HttpServletRequest request, String errorMsg) { + Errors errors; + errors = new BaseErrors(); - return forward; - } + errors.reject(errorMsg); + saveErrors(errors); + } - private AnalyzerTestMapping getAnalyzerAndTestName( - String analyzerId, String analyzerTestName, String testId) { + private void disableNavigationButtons(HttpServletRequest request) { + request.setAttribute(PREVIOUS_DISABLED, TRUE); + request.setAttribute(NEXT_DISABLED, TRUE); + } - AnalyzerTestMapping existingMapping = null; - List testMappingList = analyzerTestMappingService.getAll(); - for (AnalyzerTestMapping testMapping : testMappingList) { - if (analyzerId.equals(testMapping.getAnalyzerId()) - && analyzerTestName.equals(testMapping.getAnalyzerTestName())) { - existingMapping = testMapping; - testMapping.setTestId(testId); - break; - } + @RequestMapping(value = "/CancelAnalyzerTestName", method = RequestMethod.GET) + public ModelAndView cancelAnalyzerTestName(HttpServletRequest request, SessionStatus status) { + status.setComplete(); + return findForward(FWD_CANCEL, new AnalyzerTestNameForm()); } - return existingMapping; - } - - private void persistError(HttpServletRequest request, String errorMsg) { - Errors errors; - errors = new BaseErrors(); - - errors.reject(errorMsg); - saveErrors(errors); - } - - private void disableNavigationButtons(HttpServletRequest request) { - request.setAttribute(PREVIOUS_DISABLED, TRUE); - request.setAttribute(NEXT_DISABLED, TRUE); - } - - @RequestMapping(value = "/CancelAnalyzerTestName", method = RequestMethod.GET) - public ModelAndView cancelAnalyzerTestName(HttpServletRequest request, SessionStatus status) { - status.setComplete(); - return findForward(FWD_CANCEL, new AnalyzerTestNameForm()); - } - - @Override - protected String findLocalForward(String forward) { - if (FWD_SUCCESS.equals(forward)) { - return "analyzerTestNameDefinition"; - } else if (FWD_FAIL.equals(forward)) { - return "redirect:/AnalyzerTestNameMenu"; - } else if (FWD_SUCCESS_INSERT.equals(forward)) { - return "redirect:/AnalyzerTestNameMenu"; - } else if (FWD_FAIL_INSERT.equals(forward)) { - return "analyzerTestNameDefinition"; - } else if (FWD_CANCEL.equals(forward)) { - return "redirect:/AnalyzerTestNameMenu"; - } else { - return "PageNotFound"; + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "analyzerTestNameDefinition"; + } else if (FWD_FAIL.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "analyzerTestNameDefinition"; + } else if (FWD_CANCEL.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else { + return "PageNotFound"; + } } - } - @Override - protected String getPageTitleKey() { - return "analyzerTestName.browse.title"; - } + @Override + protected String getPageTitleKey() { + return "analyzerTestName.browse.title"; + } - @Override - protected String getPageSubtitleKey() { - return "analyzerTestName.browse.title"; - } + @Override + protected String getPageSubtitleKey() { + return "analyzerTestName.browse.title"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameMenuController.java b/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameMenuController.java index 3d725664c7..85fb0c34de 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameMenuController.java +++ b/src/main/java/org/openelisglobal/analyzerimport/controller/AnalyzerTestNameMenuController.java @@ -36,181 +36,177 @@ @Controller public class AnalyzerTestNameMenuController extends BaseMenuController { - private static final String[] ALLOWED_FIELDS = new String[] {"selectedIDs*"}; - - @Autowired private AnalyzerTestMappingService analyzerTestMappingService; - @Autowired private AnalyzerService analyzerService; - - private static final int ANALYZER_NAME = 0; - private static final int ANALYZER_TEST = 1; - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setAllowedFields(ALLOWED_FIELDS); - } - - @RequestMapping(value = "/AnalyzerTestNameMenu", method = RequestMethod.GET) - public ModelAndView showAnalyzerTestNameMenu( - HttpServletRequest request, RedirectAttributes redirectAttributes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - AnalyzerTestNameMenuForm form = new AnalyzerTestNameMenuForm(); - - addFlashMsgsToRequest(request); - - String forward = performMenuAction(form, request); - if (FWD_FAIL.equals(forward)) { - Errors errors = new BaseErrors(); - errors.reject("error.generic"); - redirectAttributes.addFlashAttribute(Constants.REQUEST_ERRORS, errors); - return findForward(forward, form); - } else { - return findForward(forward, form); - } - } + private static final String[] ALLOWED_FIELDS = new String[] { "selectedIDs*" }; - @Override - protected List createMenuList( - AdminOptionMenuForm form, HttpServletRequest request) { + @Autowired + private AnalyzerTestMappingService analyzerTestMappingService; + @Autowired + private AnalyzerService analyzerService; - request.setAttribute("menuDefinition", "AnalyzerTestNameMenuDefinition"); + private static final int ANALYZER_NAME = 0; + private static final int ANALYZER_TEST = 1; - String stringStartingRecNo = (String) request.getAttribute("startingRecNo"); - int startingRecNo = 0; - if (stringStartingRecNo != null) { - startingRecNo = Integer.parseInt(stringStartingRecNo); - if (startingRecNo < 0) { - startingRecNo = 0; - } + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); } - List mappedTestNameList = new ArrayList<>(); - List analyzerList = AnalyzerTestNameCache.getInstance().getAnalyzerNames(); - Analyzer analyzer = new Analyzer(); - - for (String analyzerName : analyzerList) { - Collection mappedTestNames = - AnalyzerTestNameCache.getInstance().getMappedTestsForAnalyzer(analyzerName).values(); - if (mappedTestNames.size() > 0) { - analyzer.setId(((MappedTestName) mappedTestNames.toArray()[0]).getAnalyzerId()); - analyzer = analyzerService.get(analyzer.getId()); - mappedTestNameList.addAll(convertedToNamedList(mappedTestNames, analyzer.getName())); - } + @RequestMapping(value = "/AnalyzerTestNameMenu", method = RequestMethod.GET) + public ModelAndView showAnalyzerTestNameMenu(HttpServletRequest request, RedirectAttributes redirectAttributes) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + AnalyzerTestNameMenuForm form = new AnalyzerTestNameMenuForm(); + + addFlashMsgsToRequest(request); + + String forward = performMenuAction(form, request); + if (FWD_FAIL.equals(forward)) { + Errors errors = new BaseErrors(); + errors.reject("error.generic"); + redirectAttributes.addFlashAttribute(Constants.REQUEST_ERRORS, errors); + return findForward(forward, form); + } else { + return findForward(forward, form); + } } - setDisplayPageBounds(request, mappedTestNameList.size(), startingRecNo); - - return mappedTestNameList.subList( - Math.min(mappedTestNameList.size(), startingRecNo - 1), - Math.min(mappedTestNameList.size(), startingRecNo + getPageSize())); + @Override + protected List createMenuList(AdminOptionMenuForm form, + HttpServletRequest request) { + + request.setAttribute("menuDefinition", "AnalyzerTestNameMenuDefinition"); + + String stringStartingRecNo = (String) request.getAttribute("startingRecNo"); + int startingRecNo = 0; + if (stringStartingRecNo != null) { + startingRecNo = Integer.parseInt(stringStartingRecNo); + if (startingRecNo < 0) { + startingRecNo = 0; + } + } + + List mappedTestNameList = new ArrayList<>(); + List analyzerList = AnalyzerTestNameCache.getInstance().getAnalyzerNames(); + Analyzer analyzer = new Analyzer(); + + for (String analyzerName : analyzerList) { + Collection mappedTestNames = AnalyzerTestNameCache.getInstance() + .getMappedTestsForAnalyzer(analyzerName).values(); + if (mappedTestNames.size() > 0) { + analyzer.setId(((MappedTestName) mappedTestNames.toArray()[0]).getAnalyzerId()); + analyzer = analyzerService.get(analyzer.getId()); + mappedTestNameList.addAll(convertedToNamedList(mappedTestNames, analyzer.getName())); + } + } + + setDisplayPageBounds(request, mappedTestNameList.size(), startingRecNo); + + return mappedTestNameList.subList(Math.min(mappedTestNameList.size(), startingRecNo - 1), + Math.min(mappedTestNameList.size(), startingRecNo + getPageSize())); + + // return mappedTestNameList; + } - // return mappedTestNameList; - } + private List convertedToNamedList(Collection mappedTestNameList, + String analyzerName) { + List namedMappingList = new ArrayList<>(); - private List convertedToNamedList( - Collection mappedTestNameList, String analyzerName) { - List namedMappingList = new ArrayList<>(); + for (MappedTestName test : mappedTestNameList) { + NamedAnalyzerTestMapping namedMapping = new NamedAnalyzerTestMapping(); + namedMapping.setActualTestName(test.getOpenElisTestName()); + namedMapping.setAnalyzerTestName(test.getAnalyzerTestName()); + namedMapping.setAnalyzerName(analyzerName); - for (MappedTestName test : mappedTestNameList) { - NamedAnalyzerTestMapping namedMapping = new NamedAnalyzerTestMapping(); - namedMapping.setActualTestName(test.getOpenElisTestName()); - namedMapping.setAnalyzerTestName(test.getAnalyzerTestName()); - namedMapping.setAnalyzerName(analyzerName); + namedMappingList.add(namedMapping); + } - namedMappingList.add(namedMapping); + return namedMappingList; } - return namedMappingList; - } + private void setDisplayPageBounds(HttpServletRequest request, int listSize, int startingRecNo) + throws LIMSRuntimeException { + request.setAttribute(MENU_TOTAL_RECORDS, String.valueOf(listSize)); + request.setAttribute(MENU_FROM_RECORD, String.valueOf(startingRecNo)); - private void setDisplayPageBounds(HttpServletRequest request, int listSize, int startingRecNo) - throws LIMSRuntimeException { - request.setAttribute(MENU_TOTAL_RECORDS, String.valueOf(listSize)); - request.setAttribute(MENU_FROM_RECORD, String.valueOf(startingRecNo)); + int numOfRecs = 0; + if (listSize != 0) { + numOfRecs = Math.min(listSize, getPageSize()); - int numOfRecs = 0; - if (listSize != 0) { - numOfRecs = Math.min(listSize, getPageSize()); + numOfRecs--; + } - numOfRecs--; + int endingRecNo = startingRecNo + numOfRecs; + request.setAttribute(MENU_TO_RECORD, String.valueOf(endingRecNo)); } - int endingRecNo = startingRecNo + numOfRecs; - request.setAttribute(MENU_TO_RECORD, String.valueOf(endingRecNo)); - } - - @Override - protected String getDeactivateDisabled() { - return "false"; - } - - @Override - protected String getEditDisabled() { - return "true"; - } - - @RequestMapping(value = "/DeleteAnalyzerTestName", method = RequestMethod.POST) - public ModelAndView showDeleteAnalyzerTestName( - HttpServletRequest request, - @ModelAttribute("form") @Valid AnalyzerTestNameMenuForm form, - BindingResult result, - RedirectAttributes redirectAttributes) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - if (result.hasErrors()) { - saveErrors(result); - return findForward(performMenuAction(form, request), form); + @Override + protected String getDeactivateDisabled() { + return "false"; } - List selectedIDs = form.getSelectedIDs(); - - // String sysUserId = getSysUserId(request); - List testMappingList = new ArrayList<>(); - - for (int i = 0; i < selectedIDs.size(); i++) { - String[] ids = selectedIDs.get(i).split(NamedAnalyzerTestMapping.getUniqueIdSeperator()); - AnalyzerTestMapping testMapping = new AnalyzerTestMapping(); - testMapping.setAnalyzerId( - AnalyzerTestNameCache.getInstance().getAnalyzerIdForName(ids[ANALYZER_NAME])); - testMapping.setAnalyzerTestName(ids[ANALYZER_TEST]); - testMapping.setSysUserId(getSysUserId(request)); - testMappingList.add(testMapping); - try { - analyzerTestMappingService.delete(testMapping); - } catch (LIMSRuntimeException e) { - LogEvent.logDebug(e); - saveErrors(result); - return findForward(performMenuAction(form, request), form); - } + @Override + protected String getEditDisabled() { + return "true"; } - AnalyzerTestNameCache.getInstance().reloadCache(); - request.setAttribute("menuDefinition", "AnalyzerTestNameDefinition"); - redirectAttributes.addFlashAttribute( - Constants.SUCCESS_MSG, MessageUtil.getMessage("message.success.delete")); - return findForward(FWD_SUCCESS_DELETE, form); - } - - @Override - protected String findLocalForward(String forward) { - if (FWD_SUCCESS.equals(forward)) { - return "analyzerMasterListsPageDefinition"; - } else if (FWD_FAIL.equals(forward)) { - return "redirect:/MasterListsPage"; - } else if (FWD_SUCCESS_DELETE.equals(forward)) { - return "redirect:/AnalyzerTestNameMenu"; - } else if (FWD_FAIL_DELETE.equals(forward)) { - return "analyzerMasterListsPageDefinition"; - } else { - return "PageNotFound"; + @RequestMapping(value = "/DeleteAnalyzerTestName", method = RequestMethod.POST) + public ModelAndView showDeleteAnalyzerTestName(HttpServletRequest request, + @ModelAttribute("form") @Valid AnalyzerTestNameMenuForm form, BindingResult result, + RedirectAttributes redirectAttributes) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + if (result.hasErrors()) { + saveErrors(result); + return findForward(performMenuAction(form, request), form); + } + + List selectedIDs = form.getSelectedIDs(); + + // String sysUserId = getSysUserId(request); + List testMappingList = new ArrayList<>(); + + for (int i = 0; i < selectedIDs.size(); i++) { + String[] ids = selectedIDs.get(i).split(NamedAnalyzerTestMapping.getUniqueIdSeperator()); + AnalyzerTestMapping testMapping = new AnalyzerTestMapping(); + testMapping.setAnalyzerId(AnalyzerTestNameCache.getInstance().getAnalyzerIdForName(ids[ANALYZER_NAME])); + testMapping.setAnalyzerTestName(ids[ANALYZER_TEST]); + testMapping.setSysUserId(getSysUserId(request)); + testMappingList.add(testMapping); + try { + analyzerTestMappingService.delete(testMapping); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + saveErrors(result); + return findForward(performMenuAction(form, request), form); + } + } + + AnalyzerTestNameCache.getInstance().reloadCache(); + request.setAttribute("menuDefinition", "AnalyzerTestNameDefinition"); + redirectAttributes.addFlashAttribute(Constants.SUCCESS_MSG, MessageUtil.getMessage("message.success.delete")); + return findForward(FWD_SUCCESS_DELETE, form); } - } - @Override - protected String getPageTitleKey() { - return "analyzerTestName.browse.title"; - } + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "analyzerMasterListsPageDefinition"; + } else if (FWD_FAIL.equals(forward)) { + return "redirect:/MasterListsPage"; + } else if (FWD_SUCCESS_DELETE.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_FAIL_DELETE.equals(forward)) { + return "analyzerMasterListsPageDefinition"; + } else { + return "PageNotFound"; + } + } - @Override - protected String getPageSubtitleKey() { - return "analyzerTestName.browse.title"; - } + @Override + protected String getPageTitleKey() { + return "analyzerTestName.browse.title"; + } + + @Override + protected String getPageSubtitleKey() { + return "analyzerTestName.browse.title"; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameMenuRestController.java b/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameMenuRestController.java new file mode 100644 index 0000000000..95bd27f497 --- /dev/null +++ b/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameMenuRestController.java @@ -0,0 +1,215 @@ +package org.openelisglobal.analyzerimport.controller.rest; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.analyzer.service.AnalyzerService; +import org.openelisglobal.analyzer.valueholder.Analyzer; +import org.openelisglobal.analyzerimport.action.beans.NamedAnalyzerTestMapping; +import org.openelisglobal.analyzerimport.form.AnalyzerTestNameMenuForm; +import org.openelisglobal.analyzerimport.service.AnalyzerTestMappingService; +import org.openelisglobal.analyzerimport.util.AnalyzerTestNameCache; +import org.openelisglobal.analyzerimport.util.MappedTestName; +import org.openelisglobal.analyzerimport.valueholder.AnalyzerTestMapping; +import org.openelisglobal.common.constants.Constants; +import org.openelisglobal.common.controller.BaseMenuController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.form.AdminOptionMenuForm; +import org.openelisglobal.common.log.LogEvent; +import org.openelisglobal.common.validator.BaseErrors; +import org.openelisglobal.internationalization.MessageUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +@RestController +@RequestMapping("/rest") +public class AnalyzerTestNameMenuRestController extends BaseMenuController { + + private static final String[] ALLOWED_FIELDS = new String[] { "selectedIDs*" }; + + @Autowired + private AnalyzerTestMappingService analyzerTestMappingService; + @Autowired + private AnalyzerService analyzerService; + + private static final int ANALYZER_NAME = 0; + private static final int ANALYZER_TEST = 1; + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/AnalyzerTestNameMenu", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity showAnalyzerTestNameMenu(HttpServletRequest request) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + AnalyzerTestNameMenuForm form = new AnalyzerTestNameMenuForm(); + + addFlashMsgsToRequest(request); + + String forward = performMenuAction(form, request); + if (FWD_FAIL.equals(forward)) { + Errors errors = new BaseErrors(); + errors.reject("error.generic"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); + } else { + return ResponseEntity.ok(form); + } + } + + @Override + protected List createMenuList(AdminOptionMenuForm form, + HttpServletRequest request) { + + request.setAttribute("menuDefinition", "AnalyzerTestNameMenuDefinition"); + + String stringStartingRecNo = (String) request.getAttribute("startingRecNo"); + int startingRecNo = 0; + if (stringStartingRecNo != null) { + startingRecNo = Integer.parseInt(stringStartingRecNo); + if (startingRecNo < 0) { + startingRecNo = 0; + } + } + + List mappedTestNameList = new ArrayList<>(); + List analyzerList = AnalyzerTestNameCache.getInstance().getAnalyzerNames(); + Analyzer analyzer = new Analyzer(); + + for (String analyzerName : analyzerList) { + Collection mappedTestNames = AnalyzerTestNameCache.getInstance() + .getMappedTestsForAnalyzer(analyzerName).values(); + if (mappedTestNames.size() > 0) { + analyzer.setId(((MappedTestName) mappedTestNames.toArray()[0]).getAnalyzerId()); + analyzer = analyzerService.get(analyzer.getId()); + mappedTestNameList.addAll(convertedToNamedList(mappedTestNames, analyzer.getName())); + } + } + + setDisplayPageBounds(request, mappedTestNameList.size(), startingRecNo); + + return mappedTestNameList.subList(Math.min(mappedTestNameList.size(), startingRecNo - 1), + Math.min(mappedTestNameList.size(), startingRecNo + getPageSize())); + + // return mappedTestNameList; + } + + private List convertedToNamedList(Collection mappedTestNameList, + String analyzerName) { + List namedMappingList = new ArrayList<>(); + + for (MappedTestName test : mappedTestNameList) { + NamedAnalyzerTestMapping namedMapping = new NamedAnalyzerTestMapping(); + namedMapping.setActualTestName(test.getOpenElisTestName()); + namedMapping.setAnalyzerTestName(test.getAnalyzerTestName()); + namedMapping.setAnalyzerName(analyzerName); + + namedMappingList.add(namedMapping); + } + + return namedMappingList; + } + + private void setDisplayPageBounds(HttpServletRequest request, int listSize, int startingRecNo) + throws LIMSRuntimeException { + request.setAttribute(MENU_TOTAL_RECORDS, String.valueOf(listSize)); + request.setAttribute(MENU_FROM_RECORD, String.valueOf(startingRecNo)); + + int numOfRecs = 0; + if (listSize != 0) { + numOfRecs = Math.min(listSize, getPageSize()); + + numOfRecs--; + } + + int endingRecNo = startingRecNo + numOfRecs; + request.setAttribute(MENU_TO_RECORD, String.valueOf(endingRecNo)); + } + + @Override + protected String getDeactivateDisabled() { + return "false"; + } + + @Override + protected String getEditDisabled() { + return "true"; + } + + @PostMapping(value = "/DeleteAnalyzerTestName", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity showDeleteAnalyzerTestName(HttpServletRequest request, + @RequestBody @Valid AnalyzerTestNameMenuForm form, BindingResult result, + RedirectAttributes redirectAttributes) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + if (result.hasErrors()) { + saveErrors(result); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); + } + + List selectedIDs = form.getSelectedIDs(); + + // String sysUserId = getSysUserId(request); + List testMappingList = new ArrayList<>(); + + for (int i = 0; i < selectedIDs.size(); i++) { + String[] ids = selectedIDs.get(i).split(NamedAnalyzerTestMapping.getUniqueIdSeperator()); + AnalyzerTestMapping testMapping = new AnalyzerTestMapping(); + testMapping.setAnalyzerId(AnalyzerTestNameCache.getInstance().getAnalyzerIdForName(ids[ANALYZER_NAME])); + testMapping.setAnalyzerTestName(ids[ANALYZER_TEST]); + testMapping.setSysUserId(getSysUserId(request)); + testMappingList.add(testMapping); + try { + analyzerTestMappingService.delete(testMapping); + } catch (LIMSRuntimeException e) { + LogEvent.logDebug(e); + saveErrors(result); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); + } + } + + AnalyzerTestNameCache.getInstance().reloadCache(); + request.setAttribute("menuDefinition", "AnalyzerTestNameDefinition"); + redirectAttributes.addFlashAttribute(Constants.SUCCESS_MSG, MessageUtil.getMessage("message.success.delete")); + return ResponseEntity.ok(form); + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "analyzerMasterListsPageDefinition"; + } else if (FWD_FAIL.equals(forward)) { + return "redirect:/MasterListsPage"; + } else if (FWD_SUCCESS_DELETE.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_FAIL_DELETE.equals(forward)) { + return "analyzerMasterListsPageDefinition"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return "analyzerTestName.browse.title"; + } + + @Override + protected String getPageSubtitleKey() { + return "analyzerTestName.browse.title"; + } +} diff --git a/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameRestController.java b/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameRestController.java new file mode 100644 index 0000000000..fc65051263 --- /dev/null +++ b/src/main/java/org/openelisglobal/analyzerimport/controller/rest/AnalyzerTestNameRestController.java @@ -0,0 +1,241 @@ +package org.openelisglobal.analyzerimport.controller.rest; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import org.openelisglobal.analyzer.service.AnalyzerService; +import org.openelisglobal.analyzer.valueholder.Analyzer; +import org.openelisglobal.analyzerimport.form.AnalyzerTestNameForm; +import org.openelisglobal.analyzerimport.service.AnalyzerTestMappingService; +import org.openelisglobal.analyzerimport.util.AnalyzerTestNameCache; +import org.openelisglobal.analyzerimport.validator.AnalyzerTestMappingValidator; +import org.openelisglobal.analyzerimport.valueholder.AnalyzerTestMapping; +import org.openelisglobal.common.controller.BaseController; +import org.openelisglobal.common.exception.LIMSRuntimeException; +import org.openelisglobal.common.form.BaseForm; +import org.openelisglobal.common.validator.BaseErrors; +import org.openelisglobal.test.service.TestService; +import org.openelisglobal.test.valueholder.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.validation.Errors; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.SessionAttributes; +import org.springframework.web.bind.support.SessionStatus; + +@RestController +@RequestMapping("/rest") +@SessionAttributes("form") +public class AnalyzerTestNameRestController extends BaseController { + + private static final String[] ALLOWED_FIELDS = new String[] { "analyzerId", "analyzerTestName", "testId" }; + + @Autowired + private AnalyzerTestMappingValidator analyzerTestMappingValidator; + @Autowired + private AnalyzerTestMappingService analyzerTestMappingService; + @Autowired + private AnalyzerService analyzerService; + @Autowired + private TestService testService; + + @ModelAttribute("form") + public AnalyzerTestNameForm initForm() { + return new AnalyzerTestNameForm(); + } + + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } + + @GetMapping(value = "/AnalyzerTestName", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity showAnalyzerTestName(HttpServletRequest request, BaseForm oldForm, + @RequestParam(value = "ID", required = false) String id) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + AnalyzerTestNameForm newForm = resetSessionFormToType(oldForm, AnalyzerTestNameForm.class); + newForm.setCancelAction("CancelAnalyzerTestName"); + + request.setAttribute(ALLOW_EDITS_KEY, "true"); + request.setAttribute(PREVIOUS_DISABLED, "true"); + request.setAttribute(NEXT_DISABLED, "true"); + + List analyzerList = getAllAnalyzers(); + List testList = getAllTests(); + + newForm.setAnalyzerList(analyzerList); + newForm.setTestList(testList); + + if (request.getParameter("ID") != null && isValidID(request.getParameter("ID"))) { + String[] splitId = request.getParameter("ID").split("#"); + newForm.setAnalyzerTestName(splitId[1]); + newForm.setTestId(splitId[2]); + newForm.setAnalyzerId(splitId[0]); + } + + if (org.apache.commons.validator.GenericValidator.isBlankOrNull(newForm.getAnalyzerId())) { + newForm.setNewMapping(true); + } else { + newForm.setNewMapping(false); + } + + return ResponseEntity.ok(newForm); + } + + private boolean isValidID(String ID) { + return ID.matches("^[0-9]+#[^#/\\<>?]*#[0-9]+"); + } + + private List getAllAnalyzers() { + return analyzerService.getAll(); + } + + private List getAllTests() { + return testService.getAllActiveTests(false); + } + + @PostMapping(value = "/AnalyzerTestName", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity showUpdateAnalyzerTestName(HttpServletRequest request, + @RequestBody @Valid AnalyzerTestNameForm form, BindingResult result, SessionStatus status) { + if (result.hasErrors()) { + return ResponseEntity.badRequest().body(result.getAllErrors()); + } + + String forward = updateAnalyzerTestName(request, form, result); + if (FWD_SUCCESS_INSERT.equals(forward)) { + status.setComplete(); + return ResponseEntity.status(HttpStatus.CREATED).body(form); + } + + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result.getAllErrors()); + } + + public String updateAnalyzerTestName(HttpServletRequest request, AnalyzerTestNameForm form, Errors errors) { + String forward = FWD_SUCCESS_INSERT; + String analyzerId = form.getAnalyzerId(); + String analyzerTestName = form.getAnalyzerTestName(); + String testId = form.getTestId(); + boolean newMapping = form.isNewMapping(); + + AnalyzerTestMapping analyzerTestNameMapping; + if (newMapping) { + analyzerTestNameMapping = new AnalyzerTestMapping(); + analyzerTestNameMapping.setAnalyzerId(analyzerId); + analyzerTestNameMapping.setAnalyzerTestName(analyzerTestName); + analyzerTestNameMapping.setTestId(testId); + analyzerTestNameMapping.setSysUserId(getSysUserId(request)); + } else { + analyzerTestNameMapping = getAnalyzerAndTestName(analyzerId, analyzerTestName, testId); + } + + try { + if (newMapping) { + analyzerTestMappingValidator.preInsertValidate(analyzerTestNameMapping, errors); + if (errors.hasErrors()) { + saveErrors(errors); + return FWD_FAIL_INSERT; + } + analyzerTestMappingService.insert(analyzerTestNameMapping); + } else { + analyzerTestMappingValidator.preUpdateValidate(analyzerTestNameMapping, errors); + if (errors.hasErrors()) { + saveErrors(errors); + return FWD_FAIL_INSERT; + } + analyzerTestNameMapping.setSysUserId(getSysUserId(request)); + analyzerTestMappingService.update(analyzerTestNameMapping); + } + + } catch (LIMSRuntimeException e) { + String errorMsg = null; + if (e.getCause() instanceof org.hibernate.StaleObjectStateException) { + errorMsg = "errors.OptimisticLockException"; + } else { + errorMsg = "errors.UpdateException"; + } + + persistError(request, errorMsg); + + disableNavigationButtons(request); + forward = FWD_FAIL_INSERT; + } + + AnalyzerTestNameCache.getInstance().reloadCache(); + + return forward; + } + + private AnalyzerTestMapping getAnalyzerAndTestName(String analyzerId, String analyzerTestName, String testId) { + + AnalyzerTestMapping existingMapping = null; + List testMappingList = analyzerTestMappingService.getAll(); + for (AnalyzerTestMapping testMapping : testMappingList) { + if (analyzerId.equals(testMapping.getAnalyzerId()) + && analyzerTestName.equals(testMapping.getAnalyzerTestName())) { + existingMapping = testMapping; + testMapping.setTestId(testId); + break; + } + } + + return existingMapping; + } + + private void persistError(HttpServletRequest request, String errorMsg) { + Errors errors; + errors = new BaseErrors(); + + errors.reject(errorMsg); + saveErrors(errors); + } + + private void disableNavigationButtons(HttpServletRequest request) { + request.setAttribute(PREVIOUS_DISABLED, TRUE); + request.setAttribute(NEXT_DISABLED, TRUE); + } + + @GetMapping(value = "/CancelAnalyzerTestName", produces = MediaType.APPLICATION_JSON_VALUE) + public AnalyzerTestNameForm cancelAnalyzerTestName(HttpServletRequest request, SessionStatus status) { + status.setComplete(); + return (new AnalyzerTestNameForm()); + } + + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "analyzerTestNameDefinition"; + } else if (FWD_FAIL.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_SUCCESS_INSERT.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else if (FWD_FAIL_INSERT.equals(forward)) { + return "analyzerTestNameDefinition"; + } else if (FWD_CANCEL.equals(forward)) { + return "redirect:/AnalyzerTestNameMenu"; + } else { + return "PageNotFound"; + } + } + + @Override + protected String getPageTitleKey() { + return "analyzerTestName.browse.title"; + } + + @Override + protected String getPageSubtitleKey() { + return "analyzerTestName.browse.title"; + } +} diff --git a/src/main/java/org/openelisglobal/analyzerimport/dao/AnalyzerTestMappingDAO.java b/src/main/java/org/openelisglobal/analyzerimport/dao/AnalyzerTestMappingDAO.java index a9ace5a86a..c7c0772ba8 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/dao/AnalyzerTestMappingDAO.java +++ b/src/main/java/org/openelisglobal/analyzerimport/dao/AnalyzerTestMappingDAO.java @@ -20,19 +20,22 @@ import org.openelisglobal.analyzerimport.valueholder.AnalyzerTestMappingPK; import org.openelisglobal.common.dao.BaseDAO; -public interface AnalyzerTestMappingDAO - extends BaseDAO { +public interface AnalyzerTestMappingDAO extends BaseDAO { - List getAllForAnalyzer(String analyzerId); + List getAllForAnalyzer(String analyzerId); - // List getAllAnalyzerTestMappings() throws LIMSRuntimeException; + // List getAllAnalyzerTestMappings() throws + // LIMSRuntimeException; - // void deleteData(List testMappingList, String currentUserId) throws - // LIMSRuntimeException; + // void deleteData(List testMappingList, String + // currentUserId) throws + // LIMSRuntimeException; - // void insertData(AnalyzerTestMapping analyzerTestMapping, String currentUserId) throws - // LIMSRuntimeException; + // void insertData(AnalyzerTestMapping analyzerTestMapping, String + // currentUserId) throws + // LIMSRuntimeException; - // void updateMapping(AnalyzerTestMapping analyzerTestNameMapping, String currentUserId) throws - // LIMSRuntimeException; + // void updateMapping(AnalyzerTestMapping analyzerTestNameMapping, String + // currentUserId) throws + // LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/analyzerimport/daoimpl/AnalyzerTestMappingDAOImpl.java b/src/main/java/org/openelisglobal/analyzerimport/daoimpl/AnalyzerTestMappingDAOImpl.java index 73b039e589..da054ee074 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/daoimpl/AnalyzerTestMappingDAOImpl.java +++ b/src/main/java/org/openelisglobal/analyzerimport/daoimpl/AnalyzerTestMappingDAOImpl.java @@ -29,29 +29,28 @@ @Component @Transactional -public class AnalyzerTestMappingDAOImpl - extends BaseDAOImpl - implements AnalyzerTestMappingDAO { +public class AnalyzerTestMappingDAOImpl extends BaseDAOImpl + implements AnalyzerTestMappingDAO { - public AnalyzerTestMappingDAOImpl() { - super(AnalyzerTestMapping.class); - } - - @Override - @Transactional(readOnly = true) - public List getAllForAnalyzer(String analyzerId) { - List list; - try { - String sql = "from AnalyzerTestMapping a where a.compoundId.analyzerId = :analyzerId"; - Query query = - entityManager.unwrap(Session.class).createQuery(sql, AnalyzerTestMapping.class); - query.setParameter("analyzerId", Integer.parseInt(analyzerId)); - list = query.list(); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AnalyzerTestMappingDAOImpl getAllForAnalyzer()", e); + public AnalyzerTestMappingDAOImpl() { + super(AnalyzerTestMapping.class); } - return list; - } + @Override + @Transactional(readOnly = true) + public List getAllForAnalyzer(String analyzerId) { + List list; + try { + String sql = "from AnalyzerTestMapping a where a.compoundId.analyzerId = :analyzerId"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, + AnalyzerTestMapping.class); + query.setParameter("analyzerId", Integer.parseInt(analyzerId)); + list = query.list(); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AnalyzerTestMappingDAOImpl getAllForAnalyzer()", e); + } + + return list; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameForm.java b/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameForm.java index c60217964f..5f1eeff374 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameForm.java +++ b/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameForm.java @@ -11,75 +11,75 @@ public class AnalyzerTestNameForm extends BaseForm { - // for display - private List analyzerList; + // for display + private List analyzerList; - // for display - private List testList; + // for display + private List testList; - @NotBlank - @Pattern(regexp = ValidationHelper.ID_REGEX) - private String analyzerId; + @NotBlank + @Pattern(regexp = ValidationHelper.ID_REGEX) + private String analyzerId; - @NotBlank - @Pattern(regexp = ValidationHelper.ID_REGEX) - private String testId; + @NotBlank + @Pattern(regexp = ValidationHelper.ID_REGEX) + private String testId; - @NotBlank - @SafeHtml(level = SafeHtml.SafeListLevel.NONE) - private String analyzerTestName; + @NotBlank + @SafeHtml(level = SafeHtml.SafeListLevel.NONE) + private String analyzerTestName; - private boolean newMapping = true; + private boolean newMapping = true; - public AnalyzerTestNameForm() { - setFormName("analyzerTestNameForm"); - } + public AnalyzerTestNameForm() { + setFormName("analyzerTestNameForm"); + } - public List getAnalyzerList() { - return analyzerList; - } + public List getAnalyzerList() { + return analyzerList; + } - public void setAnalyzerList(List analyzerList) { - this.analyzerList = analyzerList; - } + public void setAnalyzerList(List analyzerList) { + this.analyzerList = analyzerList; + } - public String getAnalyzerId() { - return analyzerId; - } + public String getAnalyzerId() { + return analyzerId; + } - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } - public List getTestList() { - return testList; - } + public List getTestList() { + return testList; + } - public void setTestList(List testList) { - this.testList = testList; - } + public void setTestList(List testList) { + this.testList = testList; + } - public String getTestId() { - return testId; - } + public String getTestId() { + return testId; + } - public void setTestId(String testId) { - this.testId = testId; - } + public void setTestId(String testId) { + this.testId = testId; + } - public String getAnalyzerTestName() { - return analyzerTestName; - } + public String getAnalyzerTestName() { + return analyzerTestName; + } - public void setAnalyzerTestName(String analyzerTestName) { - this.analyzerTestName = analyzerTestName; - } + public void setAnalyzerTestName(String analyzerTestName) { + this.analyzerTestName = analyzerTestName; + } - public boolean isNewMapping() { - return newMapping; - } + public boolean isNewMapping() { + return newMapping; + } - public void setNewMapping(boolean newMapping) { - this.newMapping = newMapping; - } + public void setNewMapping(boolean newMapping) { + this.newMapping = newMapping; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameMenuForm.java b/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameMenuForm.java index 4be1dd7a03..c17cf64b0c 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameMenuForm.java +++ b/src/main/java/org/openelisglobal/analyzerimport/form/AnalyzerTestNameMenuForm.java @@ -6,35 +6,35 @@ import org.openelisglobal.validation.annotations.SafeHtml; public class AnalyzerTestNameMenuForm extends AdminOptionMenuForm { - /** */ - private static final long serialVersionUID = -5470283912736977696L; + /** */ + private static final long serialVersionUID = -5470283912736977696L; - // for display - private List menuList; + // for display + private List menuList; - private List<@SafeHtml(level = SafeHtml.SafeListLevel.NONE) String> selectedIDs; + private List<@SafeHtml(level = SafeHtml.SafeListLevel.NONE) String> selectedIDs; - public AnalyzerTestNameMenuForm() { - setFormName("analyzerTestNameMenuForm"); - } + public AnalyzerTestNameMenuForm() { + setFormName("analyzerTestNameMenuForm"); + } - @Override - public List getMenuList() { - return menuList; - } + @Override + public List getMenuList() { + return menuList; + } - @Override - public void setMenuList(List menuList) { - this.menuList = menuList; - } + @Override + public void setMenuList(List menuList) { + this.menuList = menuList; + } - @Override - public List getSelectedIDs() { - return selectedIDs; - } + @Override + public List getSelectedIDs() { + return selectedIDs; + } - @Override - public void setSelectedIDs(List selectedIDs) { - this.selectedIDs = selectedIDs; - } + @Override + public void setSelectedIDs(List selectedIDs) { + this.selectedIDs = selectedIDs; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingService.java b/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingService.java index eaea263f13..5a5bbcd392 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingService.java +++ b/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingService.java @@ -5,8 +5,7 @@ import org.openelisglobal.analyzerimport.valueholder.AnalyzerTestMappingPK; import org.openelisglobal.common.service.BaseObjectService; -public interface AnalyzerTestMappingService - extends BaseObjectService { +public interface AnalyzerTestMappingService extends BaseObjectService { - List getAllForAnalyzer(String analyzerId); + List getAllForAnalyzer(String analyzerId); } diff --git a/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingServiceImpl.java b/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingServiceImpl.java index c6c676d251..e4d9995030 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyzerimport/service/AnalyzerTestMappingServiceImpl.java @@ -11,22 +11,23 @@ @Service public class AnalyzerTestMappingServiceImpl - extends AuditableBaseObjectServiceImpl - implements AnalyzerTestMappingService { - @Autowired protected AnalyzerTestMappingDAO baseObjectDAO; + extends AuditableBaseObjectServiceImpl + implements AnalyzerTestMappingService { + @Autowired + protected AnalyzerTestMappingDAO baseObjectDAO; - AnalyzerTestMappingServiceImpl() { - super(AnalyzerTestMapping.class); - defaultSortOrder = new ArrayList<>(); - } + AnalyzerTestMappingServiceImpl() { + super(AnalyzerTestMapping.class); + defaultSortOrder = new ArrayList<>(); + } - @Override - protected AnalyzerTestMappingDAO getBaseObjectDAO() { - return baseObjectDAO; - } + @Override + protected AnalyzerTestMappingDAO getBaseObjectDAO() { + return baseObjectDAO; + } - @Override - public List getAllForAnalyzer(String analyzerId) { - return baseObjectDAO.getAllForAnalyzer(analyzerId); - } + @Override + public List getAllForAnalyzer(String analyzerId) { + return baseObjectDAO.getAllForAnalyzer(analyzerId); + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/util/AnalyzerTestNameCache.java b/src/main/java/org/openelisglobal/analyzerimport/util/AnalyzerTestNameCache.java index 4a66194430..c925206ce0 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/util/AnalyzerTestNameCache.java +++ b/src/main/java/org/openelisglobal/analyzerimport/util/AnalyzerTestNameCache.java @@ -31,151 +31,149 @@ public class AnalyzerTestNameCache { - protected AnalyzerService analyzerService = SpringContext.getBean(AnalyzerService.class); - protected AnalyzerTestMappingService analyzerTestMappingService = - SpringContext.getBean(AnalyzerTestMappingService.class); - protected TestService testService = SpringContext.getBean(TestService.class); - - private static class SingletonHelper { - private static final AnalyzerTestNameCache INSTANCE = new AnalyzerTestNameCache(); - } - - public static final String SYSMEX_XT2000_NAME = "Sysmex XT 2000"; - public static final String COBAS_INTEGRA400_NAME = "Cobas Integra"; - public static final String FACSCALIBUR = "Facscalibur"; - public static final String EVOLIS = "Evolis"; - public static final String COBAS_TAQMAN = "Cobas Taqman"; - public static final String FACSCANTO = "FacsCanto"; - public static final String COBAS_DBS = "CobasDBS"; - public static final String COBAS_C311 = "Cobas C311"; - private final HashMap> analyzerNameToTestNameMap = - new HashMap<>(); - private Map analyzerNameToIdMap; - private Map requestTODBName = new HashMap<>(); - private boolean isMapped = false; - - private AnalyzerTestNameCache() { - requestTODBName.put("sysmex", SYSMEX_XT2000_NAME); - requestTODBName.put("cobas_integra", COBAS_INTEGRA400_NAME); - requestTODBName.put("facscalibur", FACSCALIBUR); - requestTODBName.put("evolis", EVOLIS); - requestTODBName.put("cobas_taqman", COBAS_TAQMAN); - requestTODBName.put("facscanto", FACSCANTO); - requestTODBName.put("cobasDBS", COBAS_DBS); - requestTODBName.put("cobasc311", COBAS_C311); - } - - public static AnalyzerTestNameCache getInstance() { - return SingletonHelper.INSTANCE; - } - - public String getDBNameForActionName(String actionName) { - return requestTODBName.get(actionName); - } - - public List getAnalyzerNames() { - insureMapsLoaded(); - List nameList = new ArrayList<>(); - nameList.addAll(analyzerNameToIdMap.keySet()); - return nameList; - } - - public MappedTestName getMappedTest(String analyzerName, String analyzerTestName) { - // This will look for a mapping for the analyzer and if it is found will then - // look for a mapping for the test name - Map testMap = getMappedTestsForAnalyzer(analyzerName); - - if (testMap != null) { - return testMap.get(analyzerTestName); - } + protected AnalyzerService analyzerService = SpringContext.getBean(AnalyzerService.class); + protected AnalyzerTestMappingService analyzerTestMappingService = SpringContext + .getBean(AnalyzerTestMappingService.class); + protected TestService testService = SpringContext.getBean(TestService.class); - return null; - } + private static class SingletonHelper { + private static final AnalyzerTestNameCache INSTANCE = new AnalyzerTestNameCache(); + } - public void registerPluginAnalyzer(String analyzerName, String analyzerId) { - requestTODBName.put(analyzerName, analyzerName); - if (isMapped) { - analyzerNameToIdMap.put(analyzerName, analyzerId); + public static final String SYSMEX_XT2000_NAME = "Sysmex XT 2000"; + public static final String COBAS_INTEGRA400_NAME = "Cobas Integra"; + public static final String FACSCALIBUR = "Facscalibur"; + public static final String EVOLIS = "Evolis"; + public static final String COBAS_TAQMAN = "Cobas Taqman"; + public static final String FACSCANTO = "FacsCanto"; + public static final String COBAS_DBS = "CobasDBS"; + public static final String COBAS_C311 = "Cobas C311"; + private final HashMap> analyzerNameToTestNameMap = new HashMap<>(); + private Map analyzerNameToIdMap; + private Map requestTODBName = new HashMap<>(); + private boolean isMapped = false; + + private AnalyzerTestNameCache() { + requestTODBName.put("sysmex", SYSMEX_XT2000_NAME); + requestTODBName.put("cobas_integra", COBAS_INTEGRA400_NAME); + requestTODBName.put("facscalibur", FACSCALIBUR); + requestTODBName.put("evolis", EVOLIS); + requestTODBName.put("cobas_taqman", COBAS_TAQMAN); + requestTODBName.put("facscanto", FACSCANTO); + requestTODBName.put("cobasDBS", COBAS_DBS); + requestTODBName.put("cobasc311", COBAS_C311); } - } - private synchronized void insureMapsLoaded() { - if (!isMapped) { - loadMaps(); - isMapped = true; + public static AnalyzerTestNameCache getInstance() { + return SingletonHelper.INSTANCE; } - } - public Map getMappedTestsForAnalyzer(String analyzerName) { - insureMapsLoaded(); - return analyzerNameToTestNameMap.get(analyzerName); - } + public String getDBNameForActionName(String actionName) { + return requestTODBName.get(actionName); + } - public synchronized void reloadCache() { - isMapped = false; - } + public List getAnalyzerNames() { + insureMapsLoaded(); + List nameList = new ArrayList<>(); + nameList.addAll(analyzerNameToIdMap.keySet()); + return nameList; + } - private void loadMaps() { - List analyzerList = analyzerService.getAll(); - analyzerNameToTestNameMap.clear(); + public MappedTestName getMappedTest(String analyzerName, String analyzerTestName) { + // This will look for a mapping for the analyzer and if it is found will then + // look for a mapping for the test name + Map testMap = getMappedTestsForAnalyzer(analyzerName); - analyzerNameToIdMap = new HashMap<>(); + if (testMap != null) { + return testMap.get(analyzerTestName); + } - for (Analyzer analyzer : analyzerList) { - analyzerNameToIdMap.put(analyzer.getName(), analyzer.getId()); - analyzerNameToTestNameMap.put(analyzer.getName(), new HashMap()); + return null; } - List mappingList = analyzerTestMappingService.getAll(); + public void registerPluginAnalyzer(String analyzerName, String analyzerId) { + requestTODBName.put(analyzerName, analyzerName); + if (isMapped) { + analyzerNameToIdMap.put(analyzerName, analyzerId); + } + } - for (AnalyzerTestMapping mapping : mappingList) { - MappedTestName mappedTestName = createMappedTestName(testService, mapping); + private synchronized void insureMapsLoaded() { + if (!isMapped) { + loadMaps(); + isMapped = true; + } + } - Analyzer analyzer = new Analyzer(); - analyzer.setId(mapping.getAnalyzerId()); - analyzer = analyzerService.get(analyzer.getId()); + public Map getMappedTestsForAnalyzer(String analyzerName) { + insureMapsLoaded(); + return analyzerNameToTestNameMap.get(analyzerName); + } - Map testMap = analyzerNameToTestNameMap.get(analyzer.getName()); - if (testMap != null) { - testMap.put(mapping.getAnalyzerTestName(), mappedTestName); - } + public synchronized void reloadCache() { + isMapped = false; } - } - - private MappedTestName createMappedTestName( - TestService testService, AnalyzerTestMapping mapping) { - - MappedTestName mappedTest = new MappedTestName(); - mappedTest.setAnalyzerTestName(mapping.getAnalyzerTestName()); - mappedTest.setTestId(mapping.getTestId()); - mappedTest.setAnalyzerId(mapping.getAnalyzerId()); - if (mapping.getTestId() != null) { - Test test = new Test(); - test.setId(mapping.getTestId()); - testService.getData(test); - mappedTest.setOpenElisTestName(TestServiceImpl.getUserLocalizedTestName(test)); - } else { - mappedTest.setTestId("-1"); - mappedTest.setOpenElisTestName(MessageUtil.getMessage("warning.configuration.needed")); + + private void loadMaps() { + List analyzerList = analyzerService.getAll(); + analyzerNameToTestNameMap.clear(); + + analyzerNameToIdMap = new HashMap<>(); + + for (Analyzer analyzer : analyzerList) { + analyzerNameToIdMap.put(analyzer.getName(), analyzer.getId()); + analyzerNameToTestNameMap.put(analyzer.getName(), new HashMap()); + } + + List mappingList = analyzerTestMappingService.getAll(); + + for (AnalyzerTestMapping mapping : mappingList) { + MappedTestName mappedTestName = createMappedTestName(testService, mapping); + + Analyzer analyzer = new Analyzer(); + analyzer.setId(mapping.getAnalyzerId()); + analyzer = analyzerService.get(analyzer.getId()); + + Map testMap = analyzerNameToTestNameMap.get(analyzer.getName()); + if (testMap != null) { + testMap.put(mapping.getAnalyzerTestName(), mappedTestName); + } + } } - return mappedTest; - } + private MappedTestName createMappedTestName(TestService testService, AnalyzerTestMapping mapping) { + + MappedTestName mappedTest = new MappedTestName(); + mappedTest.setAnalyzerTestName(mapping.getAnalyzerTestName()); + mappedTest.setTestId(mapping.getTestId()); + mappedTest.setAnalyzerId(mapping.getAnalyzerId()); + if (mapping.getTestId() != null) { + Test test = new Test(); + test.setId(mapping.getTestId()); + testService.getData(test); + mappedTest.setOpenElisTestName(TestServiceImpl.getUserLocalizedTestName(test)); + } else { + mappedTest.setTestId("-1"); + mappedTest.setOpenElisTestName(MessageUtil.getMessage("warning.configuration.needed")); + } + + return mappedTest; + } - public MappedTestName getEmptyMappedTestName(String analyzerName, String analyzerTestName) { - insureMapsLoaded(); - MappedTestName mappedTest = new MappedTestName(); - mappedTest.setAnalyzerTestName(analyzerTestName); - mappedTest.setTestId(null); - mappedTest.setOpenElisTestName(analyzerTestName); - mappedTest.setAnalyzerId(analyzerNameToIdMap.get(analyzerName)); + public MappedTestName getEmptyMappedTestName(String analyzerName, String analyzerTestName) { + insureMapsLoaded(); + MappedTestName mappedTest = new MappedTestName(); + mappedTest.setAnalyzerTestName(analyzerTestName); + mappedTest.setTestId(null); + mappedTest.setOpenElisTestName(analyzerTestName); + mappedTest.setAnalyzerId(analyzerNameToIdMap.get(analyzerName)); - return mappedTest; - } + return mappedTest; + } - public String getAnalyzerIdForName(String analyzerName) { - insureMapsLoaded(); + public String getAnalyzerIdForName(String analyzerName) { + insureMapsLoaded(); - return analyzerNameToIdMap.get(analyzerName); - } + return analyzerNameToIdMap.get(analyzerName); + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/util/MappedTestName.java b/src/main/java/org/openelisglobal/analyzerimport/util/MappedTestName.java index 6636079092..e2092cddcb 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/util/MappedTestName.java +++ b/src/main/java/org/openelisglobal/analyzerimport/util/MappedTestName.java @@ -16,40 +16,40 @@ package org.openelisglobal.analyzerimport.util; public class MappedTestName { - private String analyzerTestName; - private String openElisTestName; - private String analyzerId; - private String testId; - - public String getAnalyzerTestName() { - return analyzerTestName; - } - - public void setAnalyzerTestName(String analyzerTestName) { - this.analyzerTestName = analyzerTestName; - } - - public String getOpenElisTestName() { - return openElisTestName; - } - - public void setOpenElisTestName(String openElisTestName) { - this.openElisTestName = openElisTestName; - } - - public String getTestId() { - return testId; - } - - public void setTestId(String testId) { - this.testId = testId; - } - - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } - - public String getAnalyzerId() { - return analyzerId; - } + private String analyzerTestName; + private String openElisTestName; + private String analyzerId; + private String testId; + + public String getAnalyzerTestName() { + return analyzerTestName; + } + + public void setAnalyzerTestName(String analyzerTestName) { + this.analyzerTestName = analyzerTestName; + } + + public String getOpenElisTestName() { + return openElisTestName; + } + + public void setOpenElisTestName(String openElisTestName) { + this.openElisTestName = openElisTestName; + } + + public String getTestId() { + return testId; + } + + public void setTestId(String testId) { + this.testId = testId; + } + + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } + + public String getAnalyzerId() { + return analyzerId; + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/validator/AnalyzerTestMappingValidator.java b/src/main/java/org/openelisglobal/analyzerimport/validator/AnalyzerTestMappingValidator.java index 52cc47f07d..af915fd874 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/validator/AnalyzerTestMappingValidator.java +++ b/src/main/java/org/openelisglobal/analyzerimport/validator/AnalyzerTestMappingValidator.java @@ -12,48 +12,43 @@ @Component public class AnalyzerTestMappingValidator implements Validator { - protected AnalyzerTestMappingService analyzerTestMappingService = - SpringContext.getBean(AnalyzerTestMappingService.class); - - @Override - public boolean supports(Class clazz) { - return AnalyzerTestMappingValidator.class.equals(clazz); - } - - @Override - public void validate(Object target, Errors errors) { - AnalyzerTestMapping analyzerTestMapping = (AnalyzerTestMapping) target; - - ValidationHelper.validateIdField( - analyzerTestMapping.getAnalyzerId(), "analyzerId", errors, true); - - ValidationHelper.validateFieldAndCharset( - analyzerTestMapping.getAnalyzerTestName(), - "analyzerTestName", - errors, - true, - 30, - " a-zA-Z0-9�������������������������Ԍ��ܟ�\\\\\\-%#\\(\\)\\^_"); - - ValidationHelper.validateIdField(analyzerTestMapping.getTestId(), "testId", errors, true); - } - - public void preInsertValidate(AnalyzerTestMapping analyzerTestMapping, Errors errors) { - validate(analyzerTestMapping, errors); - - List testMappingList = analyzerTestMappingService.getAll(); - for (AnalyzerTestMapping testMapping : testMappingList) { - if (analyzerTestMapping.getAnalyzerId().equals(testMapping.getAnalyzerId()) - && analyzerTestMapping.getAnalyzerTestName().equals(testMapping.getAnalyzerTestName())) { - errors.reject("error.analyzer.test.name.duplicate"); - } + protected AnalyzerTestMappingService analyzerTestMappingService = SpringContext + .getBean(AnalyzerTestMappingService.class); + + @Override + public boolean supports(Class clazz) { + return AnalyzerTestMappingValidator.class.equals(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + AnalyzerTestMapping analyzerTestMapping = (AnalyzerTestMapping) target; + + ValidationHelper.validateIdField(analyzerTestMapping.getAnalyzerId(), "analyzerId", errors, true); + + ValidationHelper.validateFieldAndCharset(analyzerTestMapping.getAnalyzerTestName(), "analyzerTestName", errors, + true, 30, " a-zA-Z0-9�������������������������Ԍ��ܟ�\\\\\\-%#\\(\\)\\^_"); + + ValidationHelper.validateIdField(analyzerTestMapping.getTestId(), "testId", errors, true); } - } - public void preUpdateValidate(AnalyzerTestMapping analyzerTestMapping, Errors errors) { - validate(analyzerTestMapping, errors); + public void preInsertValidate(AnalyzerTestMapping analyzerTestMapping, Errors errors) { + validate(analyzerTestMapping, errors); + + List testMappingList = analyzerTestMappingService.getAll(); + for (AnalyzerTestMapping testMapping : testMappingList) { + if (analyzerTestMapping.getAnalyzerId().equals(testMapping.getAnalyzerId()) + && analyzerTestMapping.getAnalyzerTestName().equals(testMapping.getAnalyzerTestName())) { + errors.reject("error.analyzer.test.name.duplicate"); + } + } + } - // ValidationHelper.validateIdField(analyzerTestMapping.getId(), "id", errors, true); - ValidationHelper.validateIdField(analyzerTestMapping.getStringId(), "id", errors, true); - } + public void preUpdateValidate(AnalyzerTestMapping analyzerTestMapping, Errors errors) { + validate(analyzerTestMapping, errors); + + // ValidationHelper.validateIdField(analyzerTestMapping.getId(), "id", errors, + // true); + ValidationHelper.validateIdField(analyzerTestMapping.getStringId(), "id", errors, true); + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMapping.java b/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMapping.java index 100bc464c8..65512fb56e 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMapping.java +++ b/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMapping.java @@ -20,71 +20,71 @@ public class AnalyzerTestMapping extends BaseObject { - private static final long serialVersionUID = 1L; - - private AnalyzerTestMappingPK compoundId = new AnalyzerTestMappingPK(); - private String testId; - private String uniqueIdentifyer; - - public void setCompoundId(AnalyzerTestMappingPK compoundId) { - uniqueIdentifyer = null; - this.compoundId = compoundId; - } - - public AnalyzerTestMappingPK getCompoundId() { - return compoundId; - } - - @Override - public String getStringId() { - return compoundId == null ? "0" : compoundId.getAnalyzerId(); - } - - public void setAnalyzerId(String analyzerId) { - uniqueIdentifyer = null; - compoundId.setAnalyzerId(analyzerId); - } - - public String getAnalyzerId() { - return compoundId == null ? null : compoundId.getAnalyzerId(); - } - - public String getAnalyzerTestName() { - return compoundId == null ? null : compoundId.getAnalyzerTestName(); - } - - public void setAnalyzerTestName(String analyzerTestName) { - uniqueIdentifyer = null; - compoundId.setAnalyzerTestName(analyzerTestName); - } - - public void setTestId(String testId) { - this.testId = testId; - } - - public String getTestId() { - return testId; - } - - public void setUniqueIdentifyer(String uniqueIdentifyer) { - this.uniqueIdentifyer = uniqueIdentifyer; - } - - public String getUniqueIdentifyer() { - if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { - uniqueIdentifyer = getAnalyzerId() + "-" + getAnalyzerTestName(); + private static final long serialVersionUID = 1L; + + private AnalyzerTestMappingPK compoundId = new AnalyzerTestMappingPK(); + private String testId; + private String uniqueIdentifyer; + + public void setCompoundId(AnalyzerTestMappingPK compoundId) { + uniqueIdentifyer = null; + this.compoundId = compoundId; + } + + public AnalyzerTestMappingPK getCompoundId() { + return compoundId; + } + + @Override + public String getStringId() { + return compoundId == null ? "0" : compoundId.getAnalyzerId(); + } + + public void setAnalyzerId(String analyzerId) { + uniqueIdentifyer = null; + compoundId.setAnalyzerId(analyzerId); + } + + public String getAnalyzerId() { + return compoundId == null ? null : compoundId.getAnalyzerId(); + } + + public String getAnalyzerTestName() { + return compoundId == null ? null : compoundId.getAnalyzerTestName(); } - return uniqueIdentifyer; - } + public void setAnalyzerTestName(String analyzerTestName) { + uniqueIdentifyer = null; + compoundId.setAnalyzerTestName(analyzerTestName); + } + + public void setTestId(String testId) { + this.testId = testId; + } + + public String getTestId() { + return testId; + } + + public void setUniqueIdentifyer(String uniqueIdentifyer) { + this.uniqueIdentifyer = uniqueIdentifyer; + } + + public String getUniqueIdentifyer() { + if (GenericValidator.isBlankOrNull(uniqueIdentifyer)) { + uniqueIdentifyer = getAnalyzerId() + "-" + getAnalyzerTestName(); + } + + return uniqueIdentifyer; + } - @Override - public void setId(AnalyzerTestMappingPK id) { - setCompoundId(id); - } + @Override + public void setId(AnalyzerTestMappingPK id) { + setCompoundId(id); + } - @Override - public AnalyzerTestMappingPK getId() { - return getCompoundId(); - } + @Override + public AnalyzerTestMappingPK getId() { + return getCompoundId(); + } } diff --git a/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMappingPK.java b/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMappingPK.java index cf85683b6d..17331ef70c 100644 --- a/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMappingPK.java +++ b/src/main/java/org/openelisglobal/analyzerimport/valueholder/AnalyzerTestMappingPK.java @@ -20,37 +20,39 @@ public class AnalyzerTestMappingPK implements Serializable { - private static final long serialVersionUID = 1L; - private String analyzerId; - private String analyzerTestName; + private static final long serialVersionUID = 1L; + private String analyzerId; + private String analyzerTestName; - public String getAnalyzerId() { - return analyzerId; - } + public String getAnalyzerId() { + return analyzerId; + } - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } - public String getAnalyzerTestName() { - return analyzerTestName; - } + public String getAnalyzerTestName() { + return analyzerTestName; + } - public void setAnalyzerTestName(String analyzerTestName) { - this.analyzerTestName = analyzerTestName; - } + public void setAnalyzerTestName(String analyzerTestName) { + this.analyzerTestName = analyzerTestName; + } - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; - AnalyzerTestMappingPK that = (AnalyzerTestMappingPK) o; + AnalyzerTestMappingPK that = (AnalyzerTestMappingPK) o; - return Objects.equals(this.analyzerId, that.analyzerId) - && Objects.equals(this.analyzerTestName, that.analyzerTestName); - } + return Objects.equals(this.analyzerId, that.analyzerId) + && Objects.equals(this.analyzerTestName, that.analyzerTestName); + } - public int hashCode() { - return Objects.hash(analyzerId, analyzerTestName); - } + public int hashCode() { + return Objects.hash(analyzerId, analyzerTestName); + } } diff --git a/src/main/java/org/openelisglobal/analyzerresults/action/AnalyzerResultsPaging.java b/src/main/java/org/openelisglobal/analyzerresults/action/AnalyzerResultsPaging.java index bf9961647c..92eab0166d 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/action/AnalyzerResultsPaging.java +++ b/src/main/java/org/openelisglobal/analyzerresults/action/AnalyzerResultsPaging.java @@ -32,132 +32,127 @@ public class AnalyzerResultsPaging { - private PagingUtility> paging = new PagingUtility<>(); - private static TestItemPageHelper pagingHelper = new TestItemPageHelper(); + private PagingUtility> paging = new PagingUtility<>(); + private static TestItemPageHelper pagingHelper = new TestItemPageHelper(); - public void setDatabaseResults( - HttpServletRequest request, AnalyzerResultsForm form, List tests) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void setDatabaseResults(HttpServletRequest request, AnalyzerResultsForm form, List tests) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - paging.setDatabaseResults(request.getSession(), tests, pagingHelper); + paging.setDatabaseResults(request.getSession(), tests, pagingHelper); - List resultPage = paging.getPage(1, request.getSession()); - if (resultPage != null) { - form.setResultList(resultPage); - form.setPaging(paging.getPagingBeanWithSearchMapping(1, request.getSession())); + List resultPage = paging.getPage(1, request.getSession()); + if (resultPage != null) { + form.setResultList(resultPage); + form.setPaging(paging.getPagingBeanWithSearchMapping(1, request.getSession())); + } } - } - public void page(HttpServletRequest request, AnalyzerResultsForm form, int newPage) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + public void page(HttpServletRequest request, AnalyzerResultsForm form, int newPage) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - if (newPage < 0) { - newPage = 0; - } + if (newPage < 0) { + newPage = 0; + } - request.getSession().setAttribute(IActionConstants.SAVE_DISABLED, IActionConstants.FALSE); - List clientTests = form.getResultList(); - PagingBean bean = form.getPaging(); + request.getSession().setAttribute(IActionConstants.SAVE_DISABLED, IActionConstants.FALSE); + List clientTests = form.getResultList(); + PagingBean bean = form.getPaging(); - paging.updatePagedResults(request.getSession(), clientTests, bean, pagingHelper); + paging.updatePagedResults(request.getSession(), clientTests, bean, pagingHelper); - List resultPage = paging.getPage(newPage, request.getSession()); - if (resultPage != null) { - form.setResultList(resultPage); - form.setPaging(paging.getPagingBeanWithSearchMapping(newPage, request.getSession())); - } - } - - public void updatePagedResults(HttpServletRequest request, AnalyzerResultsForm form) { - List clientTests = form.getResultList(); - PagingBean bean = form.getPaging(); - - paging.updatePagedResults(request.getSession(), clientTests, bean, pagingHelper); - } - - public List getResults(HttpServletRequest request) { - return paging.getAllResults(request.getSession(), pagingHelper); - } - - public void setEmptyPageBean(HttpServletRequest request, IPagingForm form) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - form.setPaging(paging.getPagingBeanWithSearchMapping(0, request.getSession())); - } - - private static class TestItemPageHelper - implements IPageDivider>, - IPageUpdater>, - IPageFlattener> { - - @Override - public void createPages( - List tests, List> pagedResults) { - List page = new ArrayList<>(); - - int sampleGroupingNumber = -1; - int resultCount = 0; - - for (AnalyzerResultItem item : tests) { - if (sampleGroupingNumber != -1 && sampleGroupingNumber != item.getSampleGroupingNumber()) { - resultCount = 0; - sampleGroupingNumber = -1; - pagedResults.add(page); - page = new ArrayList<>(); - } - if (resultCount >= SpringContext.getBean(PagingProperties.class).getResultsPageSize()) { - sampleGroupingNumber = item.getSampleGroupingNumber(); + List resultPage = paging.getPage(newPage, request.getSession()); + if (resultPage != null) { + form.setResultList(resultPage); + form.setPaging(paging.getPagingBeanWithSearchMapping(newPage, request.getSession())); } + } - page.add(item); - resultCount++; - } + public void updatePagedResults(HttpServletRequest request, AnalyzerResultsForm form) { + List clientTests = form.getResultList(); + PagingBean bean = form.getPaging(); - if (!page.isEmpty() || pagedResults.isEmpty()) { - pagedResults.add(page); - } + paging.updatePagedResults(request.getSession(), clientTests, bean, pagingHelper); } - @Override - public void updateCache( - List cacheItems, List clientItems) { - for (int i = 0; i < clientItems.size(); i++) { - cacheItems.set(i, clientItems.get(i)); - } + public List getResults(HttpServletRequest request) { + return paging.getAllResults(request.getSession(), pagingHelper); } - @Override - public List flattenPages(List> pages) { - - List allResults = new ArrayList<>(); + public void setEmptyPageBean(HttpServletRequest request, IPagingForm form) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + form.setPaging(paging.getPagingBeanWithSearchMapping(0, request.getSession())); + } - for (List page : pages) { - for (AnalyzerResultItem item : page) { - allResults.add(item); + private static class TestItemPageHelper implements IPageDivider>, + IPageUpdater>, IPageFlattener> { + + @Override + public void createPages(List tests, List> pagedResults) { + List page = new ArrayList<>(); + + int sampleGroupingNumber = -1; + int resultCount = 0; + + for (AnalyzerResultItem item : tests) { + if (sampleGroupingNumber != -1 && sampleGroupingNumber != item.getSampleGroupingNumber()) { + resultCount = 0; + sampleGroupingNumber = -1; + pagedResults.add(page); + page = new ArrayList<>(); + } + if (resultCount >= SpringContext.getBean(PagingProperties.class).getResultsPageSize()) { + sampleGroupingNumber = item.getSampleGroupingNumber(); + } + + page.add(item); + resultCount++; + } + + if (!page.isEmpty() || pagedResults.isEmpty()) { + pagedResults.add(page); + } } - } - return allResults; - } - @Override - public List createSearchToPageMapping(List> allPages) { - List mappingList = new ArrayList<>(); + @Override + public void updateCache(List cacheItems, List clientItems) { + for (int i = 0; i < clientItems.size(); i++) { + cacheItems.set(i, clientItems.get(i)); + } + } - int page = 0; - for (List resultList : allPages) { - page++; - String pageString = String.valueOf(page); + @Override + public List flattenPages(List> pages) { - String currentAccession = null; + List allResults = new ArrayList<>(); - for (AnalyzerResultItem resultItem : resultList) { - if (!resultItem.getAccessionNumber().equals(currentAccession)) { - currentAccession = resultItem.getAccessionNumber(); - mappingList.add(new IdValuePair(currentAccession, pageString)); - } + for (List page : pages) { + for (AnalyzerResultItem item : page) { + allResults.add(item); + } + } + return allResults; } - } - return mappingList; + @Override + public List createSearchToPageMapping(List> allPages) { + List mappingList = new ArrayList<>(); + + int page = 0; + for (List resultList : allPages) { + page++; + String pageString = String.valueOf(page); + + String currentAccession = null; + + for (AnalyzerResultItem resultItem : resultList) { + if (!resultItem.getAccessionNumber().equals(currentAccession)) { + currentAccession = resultItem.getAccessionNumber(); + mappingList.add(new IdValuePair(currentAccession, pageString)); + } + } + } + + return mappingList; + } } - } } diff --git a/src/main/java/org/openelisglobal/analyzerresults/action/beanitems/AnalyzerResultItem.java b/src/main/java/org/openelisglobal/analyzerresults/action/beanitems/AnalyzerResultItem.java index 70cc5b8023..fca6efb0bc 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/action/beanitems/AnalyzerResultItem.java +++ b/src/main/java/org/openelisglobal/analyzerresults/action/beanitems/AnalyzerResultItem.java @@ -24,384 +24,373 @@ import org.openelisglobal.validation.annotations.ValidDate; public class AnalyzerResultItem implements Serializable { - static final long serialVersionUID = 1L; + static final long serialVersionUID = 1L; - private String id; - private String analyzerId; - private String analysisId; - private String units; - private String testName; + private String id; + private String analyzerId; + private String analysisId; + private String units; + private String testName; - // TODO move all accession number to the same format so they can be validated - // properly - // @ValidAccessionNumber(groups = { AnalyzerResultsForm.AnalyzerResuts.class }) - @Pattern( - regexp = "^[0-9a-zA-Z -:]*$", - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String accessionNumber; + // TODO move all accession number to the same format so they can be validated + // properly + // @ValidAccessionNumber(groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + @Pattern(regexp = "^[0-9a-zA-Z -:]*$", groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String accessionNumber; - @SafeHtml( - level = SafeHtml.SafeListLevel.NONE, - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String result; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE, groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String result; - private boolean isControl = false; + private boolean isControl = false; - private boolean isAccepted = false; + private boolean isAccepted = false; - private boolean isRejected = false; + private boolean isRejected = false; - private boolean isDeleted = false; + private boolean isDeleted = false; - private boolean isManual = false; + private boolean isManual = false; - private String errorMessage; + private String errorMessage; - @SafeHtml( - level = SafeHtml.SafeListLevel.NONE, - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String note; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE, groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String note; - private String statusId; - private String sampleId; + private String statusId; + private String sampleId; - @Pattern( - regexp = ValidationHelper.ID_REGEX, - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String testId; + @Pattern(regexp = ValidationHelper.ID_REGEX, groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String testId; - @ValidDate(groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String completeDate; + @ValidDate(groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String completeDate; - private boolean isPositive = false; - private String duplicateAnalyzerResultId; - private boolean isHighlighted = false; - private Timestamp lastUpdated; + private boolean isPositive = false; + private String duplicateAnalyzerResultId; + private boolean isHighlighted = false; + private Timestamp lastUpdated; - private int sampleGroupingNumber = 0; + private int sampleGroupingNumber = 0; - private boolean groupIsReadOnly = false; + private boolean groupIsReadOnly = false; - private boolean readOnly = false; + private boolean readOnly = false; - @SafeHtml( - level = SafeHtml.SafeListLevel.NONE, - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String testResultType = "N"; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE, groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String testResultType = "N"; - private boolean userChoiceReflex; - private boolean userChoicePending; - private String siblingReflexKey; + private boolean userChoiceReflex; + private boolean userChoicePending; + private String siblingReflexKey; - @SafeHtml( - level = SafeHtml.SafeListLevel.NONE, - groups = {AnalyzerResultsForm.AnalyzerResuts.class}) - private String reflexSelectionId; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE, groups = { AnalyzerResultsForm.AnalyzerResuts.class }) + private String reflexSelectionId; - private String selectionOneText = ""; - private String selectionOneValue = ""; - private String selectionTwoText = ""; - private String selectionTwoValue = ""; - private boolean nonconforming = false; - private String significantDigits = ""; + private String selectionOneText = ""; + private String selectionOneValue = ""; + private String selectionTwoText = ""; + private String selectionTwoValue = ""; + private boolean nonconforming = false; + private String significantDigits = ""; - public String getSignificantDigits() { - return significantDigits; - } + public String getSignificantDigits() { + return significantDigits; + } - public void setSignificantDigits(String significantDigits) { - this.significantDigits = significantDigits; - } + public void setSignificantDigits(String significantDigits) { + this.significantDigits = significantDigits; + } - private List dictionaryResultList; + private List dictionaryResultList; - public AnalyzerResultItem() {} + public AnalyzerResultItem() { + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getTestName() { - return testName; - } + public String getTestName() { + return testName; + } - public void setTestName(String testName) { - this.testName = testName; - } + public void setTestName(String testName) { + this.testName = testName; + } - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } - public String getAnalyzerId() { - return analyzerId; - } + public String getAnalyzerId() { + return analyzerId; + } - public void setAnalysisId(String analysisId) { - this.analysisId = analysisId; - } + public void setAnalysisId(String analysisId) { + this.analysisId = analysisId; + } - public String getAnalysisId() { - return analysisId; - } + public String getAnalysisId() { + return analysisId; + } - public void setUnits(String units) { - this.units = units; - } + public void setUnits(String units) { + this.units = units; + } - public String getUnits() { - return units; - } + public String getUnits() { + return units; + } - public void setAccessionNumber(String accessionNumber) { - this.accessionNumber = accessionNumber; - } + public void setAccessionNumber(String accessionNumber) { + this.accessionNumber = accessionNumber; + } - public String getAccessionNumber() { - return accessionNumber; - } + public String getAccessionNumber() { + return accessionNumber; + } - public void setResult(String result) { - this.result = result; - } + public void setResult(String result) { + this.result = result; + } - public String getResult() { - return result; - } + public String getResult() { + return result; + } - public void setIsControl(boolean isControl) { - this.isControl = isControl; - } + public void setIsControl(boolean isControl) { + this.isControl = isControl; + } - public boolean getIsControl() { - return isControl; - } + public boolean getIsControl() { + return isControl; + } - public void setIsAccepted(boolean isAccepted) { - this.isAccepted = isAccepted; - } + public void setIsAccepted(boolean isAccepted) { + this.isAccepted = isAccepted; + } - public boolean getIsAccepted() { - return isAccepted; - } + public boolean getIsAccepted() { + return isAccepted; + } - public void setIsRejected(boolean isRejected) { - this.isRejected = isRejected; - } + public void setIsRejected(boolean isRejected) { + this.isRejected = isRejected; + } - public boolean getIsRejected() { - return isRejected; - } + public boolean getIsRejected() { + return isRejected; + } - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } - public String getErrorMessage() { - return errorMessage; - } + public String getErrorMessage() { + return errorMessage; + } - public void setNote(String note) { - this.note = note; - } + public void setNote(String note) { + this.note = note; + } - public String getNote() { - return note; - } + public String getNote() { + return note; + } - public void setStatusId(String statusId) { - this.statusId = statusId; - } + public void setStatusId(String statusId) { + this.statusId = statusId; + } - public String getStatusId() { - return statusId; - } + public String getStatusId() { + return statusId; + } - public void setSampleId(String sampleId) { - this.sampleId = sampleId; - } + public void setSampleId(String sampleId) { + this.sampleId = sampleId; + } - public String getSampleId() { - return sampleId; - } + public String getSampleId() { + return sampleId; + } - public void setTestId(String testId) { - this.testId = testId; - } + public void setTestId(String testId) { + this.testId = testId; + } - public String getTestId() { - return testId; - } + public String getTestId() { + return testId; + } - public void setCompleteDate(String completeDate) { - this.completeDate = completeDate; - } + public void setCompleteDate(String completeDate) { + this.completeDate = completeDate; + } - public String getCompleteDate() { - return completeDate; - } + public String getCompleteDate() { + return completeDate; + } - public void setPositive(boolean isPositive) { - this.isPositive = isPositive; - } + public void setPositive(boolean isPositive) { + this.isPositive = isPositive; + } - public boolean getPositive() { - return isPositive; - } + public boolean getPositive() { + return isPositive; + } - public void setDuplicateAnalyzerResultId(String duplicateAnalyzerResultId) { - this.duplicateAnalyzerResultId = duplicateAnalyzerResultId; - } + public void setDuplicateAnalyzerResultId(String duplicateAnalyzerResultId) { + this.duplicateAnalyzerResultId = duplicateAnalyzerResultId; + } - public String getDuplicateAnalyzerResultId() { - return duplicateAnalyzerResultId; - } + public String getDuplicateAnalyzerResultId() { + return duplicateAnalyzerResultId; + } - public void setIsHighlighted(boolean isHighlighted) { - this.isHighlighted = isHighlighted; - } + public void setIsHighlighted(boolean isHighlighted) { + this.isHighlighted = isHighlighted; + } - public boolean getIsHighlighted() { - return isHighlighted && readOnly; - } + public boolean getIsHighlighted() { + return isHighlighted && readOnly; + } - public void setLastUpdated(Timestamp lastupdated) { - lastUpdated = lastupdated; - } + public void setLastUpdated(Timestamp lastupdated) { + lastUpdated = lastupdated; + } - public Timestamp getLastUpdated() { - return lastUpdated; - } + public Timestamp getLastUpdated() { + return lastUpdated; + } - public void setSampleGroupingNumber(int sampleGroupingNumber) { - this.sampleGroupingNumber = sampleGroupingNumber; - } + public void setSampleGroupingNumber(int sampleGroupingNumber) { + this.sampleGroupingNumber = sampleGroupingNumber; + } - public int getSampleGroupingNumber() { - return sampleGroupingNumber; - } + public int getSampleGroupingNumber() { + return sampleGroupingNumber; + } - public void setManual(boolean isManual) { - this.isManual = isManual; - } + public void setManual(boolean isManual) { + this.isManual = isManual; + } - public boolean getManual() { - return isManual; - } + public boolean getManual() { + return isManual; + } - public void setGroupIsReadOnly(boolean groupIsReadOnly) { - this.groupIsReadOnly = groupIsReadOnly; - } + public void setGroupIsReadOnly(boolean groupIsReadOnly) { + this.groupIsReadOnly = groupIsReadOnly; + } - public boolean isGroupIsReadOnly() { - return groupIsReadOnly; - } + public boolean isGroupIsReadOnly() { + return groupIsReadOnly; + } - public void setReadOnly(boolean readOnly) { - this.readOnly = readOnly; - } + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } - public boolean isReadOnly() { - return readOnly; - } + public boolean isReadOnly() { + return readOnly; + } - public void setTestResultType(String testResultType) { - this.testResultType = testResultType; - } + public void setTestResultType(String testResultType) { + this.testResultType = testResultType; + } - public String getTestResultType() { - return testResultType; - } + public String getTestResultType() { + return testResultType; + } - public void setDictionaryResultList(List dictionaryResultList) { - this.dictionaryResultList = dictionaryResultList; - } + public void setDictionaryResultList(List dictionaryResultList) { + this.dictionaryResultList = dictionaryResultList; + } - public List getDictionaryResultList() { - return dictionaryResultList; - } + public List getDictionaryResultList() { + return dictionaryResultList; + } - public boolean isUserChoiceReflex() { - return userChoiceReflex; - } + public boolean isUserChoiceReflex() { + return userChoiceReflex; + } - public void setUserChoiceReflex(boolean userChoiceReflex) { - this.userChoiceReflex = userChoiceReflex; - } + public void setUserChoiceReflex(boolean userChoiceReflex) { + this.userChoiceReflex = userChoiceReflex; + } - public String getSiblingReflexKey() { - return siblingReflexKey; - } + public String getSiblingReflexKey() { + return siblingReflexKey; + } - public void setSiblingReflexKey(String siblingReflexKey) { - this.siblingReflexKey = siblingReflexKey; - } + public void setSiblingReflexKey(String siblingReflexKey) { + this.siblingReflexKey = siblingReflexKey; + } - public String getReflexSelectionId() { - return reflexSelectionId; - } + public String getReflexSelectionId() { + return reflexSelectionId; + } - public void setReflexSelectionId(String reflexSelectionId) { - this.reflexSelectionId = reflexSelectionId; - } + public void setReflexSelectionId(String reflexSelectionId) { + this.reflexSelectionId = reflexSelectionId; + } - public String getSelectionOneText() { - return selectionOneText; - } + public String getSelectionOneText() { + return selectionOneText; + } - public void setSelectionOneText(String selectionOneText) { - this.selectionOneText = selectionOneText; - } + public void setSelectionOneText(String selectionOneText) { + this.selectionOneText = selectionOneText; + } - public String getSelectionOneValue() { - return selectionOneValue; - } + public String getSelectionOneValue() { + return selectionOneValue; + } - public void setSelectionOneValue(String selectionOneValue) { - this.selectionOneValue = selectionOneValue; - } + public void setSelectionOneValue(String selectionOneValue) { + this.selectionOneValue = selectionOneValue; + } - public String getSelectionTwoText() { - return selectionTwoText; - } + public String getSelectionTwoText() { + return selectionTwoText; + } - public void setSelectionTwoText(String selectionTwoText) { - this.selectionTwoText = selectionTwoText; - } + public void setSelectionTwoText(String selectionTwoText) { + this.selectionTwoText = selectionTwoText; + } - public String getSelectionTwoValue() { - return selectionTwoValue; - } + public String getSelectionTwoValue() { + return selectionTwoValue; + } - public void setSelectionTwoValue(String selectionTwoValue) { - this.selectionTwoValue = selectionTwoValue; - } + public void setSelectionTwoValue(String selectionTwoValue) { + this.selectionTwoValue = selectionTwoValue; + } - public boolean isUserChoicePending() { - return userChoicePending; - } + public boolean isUserChoicePending() { + return userChoicePending; + } - public void setUserChoicePending(boolean userChoicePending) { - this.userChoicePending = userChoicePending; - } + public void setUserChoicePending(boolean userChoicePending) { + this.userChoicePending = userChoicePending; + } - public boolean getIsDeleted() { - return isDeleted; - } + public boolean getIsDeleted() { + return isDeleted; + } - public void setIsDeleted(boolean isDeleted) { - this.isDeleted = isDeleted; - } + public void setIsDeleted(boolean isDeleted) { + this.isDeleted = isDeleted; + } - public boolean isNonconforming() { - return nonconforming; - } + public boolean isNonconforming() { + return nonconforming; + } - public void setNonconforming(boolean nonconforming) { - this.nonconforming = nonconforming; - } + public void setNonconforming(boolean nonconforming) { + this.nonconforming = nonconforming; + } } diff --git a/src/main/java/org/openelisglobal/analyzerresults/dao/AnalyzerResultsDAO.java b/src/main/java/org/openelisglobal/analyzerresults/dao/AnalyzerResultsDAO.java index 9d4f1a1594..d2c2720d4a 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/dao/AnalyzerResultsDAO.java +++ b/src/main/java/org/openelisglobal/analyzerresults/dao/AnalyzerResultsDAO.java @@ -21,20 +21,21 @@ public interface AnalyzerResultsDAO extends BaseDAO { - // public List getResultsbyAnalyzer(String analyzerId) throws - // LIMSRuntimeException; + // public List getResultsbyAnalyzer(String analyzerId) throws + // LIMSRuntimeException; - // public void insertAnalyzerResults(List results, String sysUserId) throws - // LIMSRuntimeException; + // public void insertAnalyzerResults(List results, String + // sysUserId) throws + // LIMSRuntimeException; - // public void updateData(AnalyzerResults results) throws LIMSRuntimeException; + // public void updateData(AnalyzerResults results) throws LIMSRuntimeException; - // public void getData(AnalyzerResults results) throws LIMSRuntimeException; + // public void getData(AnalyzerResults results) throws LIMSRuntimeException; - public AnalyzerResults readAnalyzerResults(String idString); + public AnalyzerResults readAnalyzerResults(String idString); - public List getDuplicateResultByAccessionAndTest(AnalyzerResults result); + public List getDuplicateResultByAccessionAndTest(AnalyzerResults result); - // public void deleteAll(List deletableAnalyzerResults) throws - // LIMSRuntimeException; + // public void deleteAll(List deletableAnalyzerResults) throws + // LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/analyzerresults/daoimpl/AnalyzerResultsDAOImpl.java b/src/main/java/org/openelisglobal/analyzerresults/daoimpl/AnalyzerResultsDAOImpl.java index 8a2d87567a..ce1ec535dc 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/daoimpl/AnalyzerResultsDAOImpl.java +++ b/src/main/java/org/openelisglobal/analyzerresults/daoimpl/AnalyzerResultsDAOImpl.java @@ -29,49 +29,45 @@ @Component @Transactional -public class AnalyzerResultsDAOImpl extends BaseDAOImpl - implements AnalyzerResultsDAO { +public class AnalyzerResultsDAOImpl extends BaseDAOImpl implements AnalyzerResultsDAO { - public AnalyzerResultsDAOImpl() { - super(AnalyzerResults.class); - } + public AnalyzerResultsDAOImpl() { + super(AnalyzerResults.class); + } - @Override - @Transactional(readOnly = true) - public List getDuplicateResultByAccessionAndTest(AnalyzerResults result) { - try { + @Override + @Transactional(readOnly = true) + public List getDuplicateResultByAccessionAndTest(AnalyzerResults result) { + try { - List list = new ArrayList<>(); + List list = new ArrayList<>(); - String sql = - "from AnalyzerResults a where a.analyzerId = :analyzerId and " - + "a.accessionNumber = :assessionNumber and " - + "a.testName = :testName"; - Query query = - entityManager.unwrap(Session.class).createQuery(sql, AnalyzerResults.class); - query.setParameter("analyzerId", Integer.parseInt(result.getAnalyzerId())); - query.setParameter("assessionNumber", result.getAccessionNumber()); - query.setParameter("testName", result.getTestName()); + String sql = "from AnalyzerResults a where a.analyzerId = :analyzerId and " + + "a.accessionNumber = :assessionNumber and " + "a.testName = :testName"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, AnalyzerResults.class); + query.setParameter("analyzerId", Integer.parseInt(result.getAnalyzerId())); + query.setParameter("assessionNumber", result.getAccessionNumber()); + query.setParameter("testName", result.getTestName()); - list = query.list(); + list = query.list(); - return list.size() > 0 ? list : null; + return list.size() > 0 ? list : null; - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in duplicateAnalyzerResultsExists()", e); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in duplicateAnalyzerResultsExists()", e); + } } - } - @Override - public AnalyzerResults readAnalyzerResults(String idString) throws LIMSRuntimeException { - AnalyzerResults data = null; - try { - data = entityManager.unwrap(Session.class).get(AnalyzerResults.class, idString); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AnalyzerResults readAnalyzerResults()", e); + @Override + public AnalyzerResults readAnalyzerResults(String idString) throws LIMSRuntimeException { + AnalyzerResults data = null; + try { + data = entityManager.unwrap(Session.class).get(AnalyzerResults.class, idString); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AnalyzerResults readAnalyzerResults()", e); + } + return data; } - return data; - } } diff --git a/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsService.java b/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsService.java index 861fabb30d..225a1671f1 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsService.java +++ b/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsService.java @@ -7,14 +7,12 @@ public interface AnalyzerResultsService extends BaseObjectService { - AnalyzerResults readAnalyzerResults(String idString); + AnalyzerResults readAnalyzerResults(String idString); - List getResultsbyAnalyzer(String analyzerId); + List getResultsbyAnalyzer(String analyzerId); - void insertAnalyzerResults(List results, String sysUserId); + void insertAnalyzerResults(List results, String sysUserId); - void persistAnalyzerResults( - List deletableAnalyzerResults, - List sampleGroupList, - String sysUserId); + void persistAnalyzerResults(List deletableAnalyzerResults, List sampleGroupList, + String sysUserId); } diff --git a/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsServiceImpl.java b/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsServiceImpl.java index f899734eab..28bcfd42d4 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsServiceImpl.java +++ b/src/main/java/org/openelisglobal/analyzerresults/service/AnalyzerResultsServiceImpl.java @@ -30,205 +30,207 @@ import org.springframework.transaction.annotation.Transactional; @Service -public class AnalyzerResultsServiceImpl - extends AuditableBaseObjectServiceImpl - implements AnalyzerResultsService { - @Autowired protected AnalyzerResultsDAO baseObjectDAO; - - @Autowired private NoteService noteService; - @Autowired private SampleHumanService sampleHumanService; - @Autowired private SampleItemService sampleItemService; - @Autowired private SampleService sampleService; - @Autowired private AnalysisService analysisService; - @Autowired private ResultService resultService; - - AnalyzerResultsServiceImpl() { - super(AnalyzerResults.class); - } - - @Override - protected AnalyzerResultsDAO getBaseObjectDAO() { - return baseObjectDAO; - } - - @Override - @Transactional(readOnly = true) - public List getResultsbyAnalyzer(String analyzerId) { - return baseObjectDAO.getAllMatchingOrdered( - "analyzerId", Integer.parseInt(analyzerId), "id", false); - } - - @Override - public AnalyzerResults readAnalyzerResults(String idString) { - return getBaseObjectDAO().readAnalyzerResults(idString); - } - - @Override - public void insertAnalyzerResults(List results, String sysUserId) { - try { - for (AnalyzerResults result : results) { - boolean duplicateByAccessionAndTestOnly = false; - List previousResults = - baseObjectDAO.getDuplicateResultByAccessionAndTest(result); - AnalyzerResults previousResult = null; - - // This next block may seem more complicated then it need be but it covers the - // case where there may be a third duplicate - // and it covers rereading the same file - if (previousResults != null) { - duplicateByAccessionAndTestOnly = true; - for (AnalyzerResults foundResult : previousResults) { - previousResult = foundResult; - if (foundResult.getCompleteDate() != null - && foundResult.getCompleteDate().equals(result.getCompleteDate())) { - duplicateByAccessionAndTestOnly = false; - break; - } - } - } +public class AnalyzerResultsServiceImpl extends AuditableBaseObjectServiceImpl + implements AnalyzerResultsService { + @Autowired + protected AnalyzerResultsDAO baseObjectDAO; + + @Autowired + private NoteService noteService; + @Autowired + private SampleHumanService sampleHumanService; + @Autowired + private SampleItemService sampleItemService; + @Autowired + private SampleService sampleService; + @Autowired + private AnalysisService analysisService; + @Autowired + private ResultService resultService; + + AnalyzerResultsServiceImpl() { + super(AnalyzerResults.class); + } - if (duplicateByAccessionAndTestOnly && previousResult != null) { - result.setDuplicateAnalyzerResultId(previousResult.getId()); - result.setReadOnly(true); - } + @Override + protected AnalyzerResultsDAO getBaseObjectDAO() { + return baseObjectDAO; + } + + @Override + @Transactional(readOnly = true) + public List getResultsbyAnalyzer(String analyzerId) { + return baseObjectDAO.getAllMatchingOrdered("analyzerId", Integer.parseInt(analyzerId), "id", false); + } - if (previousResults == null || duplicateByAccessionAndTestOnly) { - result.setSysUserId(sysUserId); - String id = insert(result); - result.setId(id); + @Override + public AnalyzerResults readAnalyzerResults(String idString) { + return getBaseObjectDAO().readAnalyzerResults(idString); + } - if (duplicateByAccessionAndTestOnly && previousResult != null) { - previousResult.setDuplicateAnalyzerResultId(id); - previousResult.setSysUserId(sysUserId); - } + @Override + public void insertAnalyzerResults(List results, String sysUserId) { + try { + for (AnalyzerResults result : results) { + boolean duplicateByAccessionAndTestOnly = false; + List previousResults = baseObjectDAO.getDuplicateResultByAccessionAndTest(result); + AnalyzerResults previousResult = null; + + // This next block may seem more complicated then it need be but it covers the + // case where there may be a third duplicate + // and it covers rereading the same file + if (previousResults != null) { + duplicateByAccessionAndTestOnly = true; + for (AnalyzerResults foundResult : previousResults) { + previousResult = foundResult; + if (foundResult.getCompleteDate() != null + && foundResult.getCompleteDate().equals(result.getCompleteDate())) { + duplicateByAccessionAndTestOnly = false; + break; + } + } + } + + if (duplicateByAccessionAndTestOnly && previousResult != null) { + result.setDuplicateAnalyzerResultId(previousResult.getId()); + result.setReadOnly(true); + } + + if (previousResults == null || duplicateByAccessionAndTestOnly) { + result.setSysUserId(sysUserId); + String id = insert(result); + result.setId(id); + + if (duplicateByAccessionAndTestOnly && previousResult != null) { + previousResult.setDuplicateAnalyzerResultId(id); + previousResult.setSysUserId(sysUserId); + } + + if (duplicateByAccessionAndTestOnly) { + update(previousResult); + } + } + } - if (duplicateByAccessionAndTestOnly) { - update(previousResult); - } + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AnalyzerResult insertAnalyzerResult()", e); } - } - - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AnalyzerResult insertAnalyzerResult()", e); } - } - - @Override - @Transactional - public void persistAnalyzerResults( - List deletableAnalyzerResults, - List sampleGroupList, - String sysUserId) { - removeHandledResultsFromAnalyzerResults(deletableAnalyzerResults, sysUserId); - - insertResults(sampleGroupList, sysUserId); - } - - private void removeHandledResultsFromAnalyzerResults( - List deletableAnalyzerResults, String sysUserId) { - for (AnalyzerResults currentAnalyzerResult : deletableAnalyzerResults) { - delete(currentAnalyzerResult.getId(), sysUserId); + + @Override + @Transactional + public void persistAnalyzerResults(List deletableAnalyzerResults, + List sampleGroupList, String sysUserId) { + removeHandledResultsFromAnalyzerResults(deletableAnalyzerResults, sysUserId); + + insertResults(sampleGroupList, sysUserId); } - } - - private boolean insertResults(List sampleGroupList, String sysUserId) { - for (SampleGrouping grouping : sampleGroupList) { - if (grouping.addSample) { - // try { - sampleService.insertDataWithAccessionNumber(grouping.sample); - // } catch (LIMSRuntimeException e) { - // Errors errors = new BaseErrors(); - // String errorMsg = "warning.duplicate.accession"; - // errors.reject(errorMsg, new String[] { grouping.sample.getAccessionNumber() }, - // errorMsg); - // saveErrors(errors); - // return false; - // } - } else if (grouping.updateSample) { - sampleService.update(grouping.sample); - } - - String sampleId = grouping.sample.getId(); - - if (grouping.addSample) { - grouping.sampleHuman.setSampleId(sampleId); - sampleHumanService.insert(grouping.sampleHuman); - - RecordStatus patientStatus = - grouping.statusSet.getPatientRecordStatus() == null ? RecordStatus.NotRegistered : null; - RecordStatus sampleStatus = - grouping.statusSet.getSampleRecordStatus() == null ? RecordStatus.NotRegistered : null; - SpringContext.getBean(IStatusService.class) - .persistRecordStatusForSample( - grouping.sample, sampleStatus, grouping.patient, patientStatus, sysUserId); - } - - if (grouping.addSampleItem) { - grouping.sampleItem.setSample(grouping.sample); - sampleItemService.insert(grouping.sampleItem); - } - - for (int i = 0; i < grouping.analysisList.size(); i++) { - - Analysis analysis = grouping.analysisList.get(i); - if (GenericValidator.isBlankOrNull(analysis.getId())) { - analysis.setSampleItem(grouping.sampleItem); - analysisService.insert(analysis); - } else { - analysisService.update(analysis); - } - Result result = grouping.resultList.get(i); - if (GenericValidator.isBlankOrNull(result.getId())) { - result.setAnalysis(analysis); - setAnalyte(result); - resultService.insert(result); - } else { - resultService.update(result); + private void removeHandledResultsFromAnalyzerResults(List deletableAnalyzerResults, + String sysUserId) { + for (AnalyzerResults currentAnalyzerResult : deletableAnalyzerResults) { + delete(currentAnalyzerResult.getId(), sysUserId); } + } - Note note = grouping.noteList.get(i); + private boolean insertResults(List sampleGroupList, String sysUserId) { + for (SampleGrouping grouping : sampleGroupList) { + if (grouping.addSample) { + // try { + sampleService.insertDataWithAccessionNumber(grouping.sample); + // } catch (LIMSRuntimeException e) { + // Errors errors = new BaseErrors(); + // String errorMsg = "warning.duplicate.accession"; + // errors.reject(errorMsg, new String[] { grouping.sample.getAccessionNumber() + // }, + // errorMsg); + // saveErrors(errors); + // return false; + // } + } else if (grouping.updateSample) { + sampleService.update(grouping.sample); + } + + String sampleId = grouping.sample.getId(); + + if (grouping.addSample) { + grouping.sampleHuman.setSampleId(sampleId); + sampleHumanService.insert(grouping.sampleHuman); + + RecordStatus patientStatus = grouping.statusSet.getPatientRecordStatus() == null + ? RecordStatus.NotRegistered + : null; + RecordStatus sampleStatus = grouping.statusSet.getSampleRecordStatus() == null + ? RecordStatus.NotRegistered + : null; + SpringContext.getBean(IStatusService.class).persistRecordStatusForSample(grouping.sample, sampleStatus, + grouping.patient, patientStatus, sysUserId); + } + + if (grouping.addSampleItem) { + grouping.sampleItem.setSample(grouping.sample); + sampleItemService.insert(grouping.sampleItem); + } - if (note != null) { - note.setReferenceId(result.getId()); - noteService.insert(note); + for (int i = 0; i < grouping.analysisList.size(); i++) { + + Analysis analysis = grouping.analysisList.get(i); + if (GenericValidator.isBlankOrNull(analysis.getId())) { + analysis.setSampleItem(grouping.sampleItem); + analysisService.insert(analysis); + } else { + analysisService.update(analysis); + } + + Result result = grouping.resultList.get(i); + if (GenericValidator.isBlankOrNull(result.getId())) { + result.setAnalysis(analysis); + setAnalyte(result); + resultService.insert(result); + } else { + resultService.update(result); + } + + Note note = grouping.noteList.get(i); + + if (note != null) { + note.setReferenceId(result.getId()); + noteService.insert(note); + } + } } - } + + TestReflexUtil testReflexUtil = new TestReflexUtil(); + testReflexUtil.addNewTestsToDBForReflexTests(convertGroupListToTestReflexBeans(sampleGroupList), sysUserId); + + return true; } - TestReflexUtil testReflexUtil = new TestReflexUtil(); - testReflexUtil.addNewTestsToDBForReflexTests( - convertGroupListToTestReflexBeans(sampleGroupList), sysUserId); - - return true; - } - - private List convertGroupListToTestReflexBeans( - List sampleGroupList) { - List reflexBeanList = new ArrayList<>(); - - for (SampleGrouping sampleGroup : sampleGroupList) { - if (sampleGroup.accepted) { - for (Result result : sampleGroup.resultList) { - TestReflexBean reflex = new TestReflexBean(); - reflex.setPatient(sampleGroup.patient); - reflex.setTriggersToSelectedReflexesMap(sampleGroup.triggersToSelectedReflexesMap); - reflex.setResult(result); - reflex.setSample(sampleGroup.sample); - reflexBeanList.add(reflex); + private List convertGroupListToTestReflexBeans(List sampleGroupList) { + List reflexBeanList = new ArrayList<>(); + + for (SampleGrouping sampleGroup : sampleGroupList) { + if (sampleGroup.accepted) { + for (Result result : sampleGroup.resultList) { + TestReflexBean reflex = new TestReflexBean(); + reflex.setPatient(sampleGroup.patient); + reflex.setTriggersToSelectedReflexesMap(sampleGroup.triggersToSelectedReflexesMap); + reflex.setResult(result); + reflex.setSample(sampleGroup.sample); + reflexBeanList.add(reflex); + } + } } - } - } - return reflexBeanList; - } + return reflexBeanList; + } - private void setAnalyte(Result result) { - TestAnalyte testAnalyte = ResultUtil.getTestAnalyteForResult(result); + private void setAnalyte(Result result) { + TestAnalyte testAnalyte = ResultUtil.getTestAnalyteForResult(result); - if (testAnalyte != null) { - result.setAnalyte(testAnalyte.getAnalyte()); + if (testAnalyte != null) { + result.setAnalyte(testAnalyte.getAnalyte()); + } } - } } diff --git a/src/main/java/org/openelisglobal/analyzerresults/valueholder/AnalyzerResults.java b/src/main/java/org/openelisglobal/analyzerresults/valueholder/AnalyzerResults.java index 15747988e1..0df7786e28 100644 --- a/src/main/java/org/openelisglobal/analyzerresults/valueholder/AnalyzerResults.java +++ b/src/main/java/org/openelisglobal/analyzerresults/valueholder/AnalyzerResults.java @@ -19,122 +19,122 @@ public class AnalyzerResults extends BaseObject implements Cloneable { - private static final long serialVersionUID = 1L; - - private String id; - private String analyzerId; - private String accessionNumber; - private String testName; - private String result; - private String units; - private String duplicateAnalyzerResultId; - private boolean isControl = false; - private boolean isReadOnly = false; - private String testId; - private String resultType = "N"; - private Timestamp completeDate; - - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - public void setId(String id) { - this.id = id; - } - - public String getId() { - return this.id; - } - - public void setAnalyzerId(String analyzerId) { - this.analyzerId = analyzerId; - } - - public String getAnalyzerId() { - return analyzerId; - } - - public void setAccessionNumber(String accessionNumber) { - this.accessionNumber = accessionNumber.replaceAll("\'", ""); - } - - public String getAccessionNumber() { - return accessionNumber; - } - - public void setTestName(String testName) { - this.testName = testName; - } - - public String getTestName() { - return testName; - } - - public void setResult(String result) { - this.result = result; - } - - public String getResult() { - return this.result; - } - - public void setUnits(String units) { - this.units = units; - } - - public String getUnits() { - return units; - } - - public void setIsControl(boolean isControl) { - this.isControl = isControl; - } - - public boolean getIsControl() { - return isControl; - } - - public void setCompleteDate(Timestamp completeDate) { - this.completeDate = completeDate; - } - - public Timestamp getCompleteDate() { - return completeDate; - } - - public String getCompleteDateForDisplay() { - return DateUtil.convertTimestampToStringDate(completeDate); - } - - public void setDuplicateAnalyzerResultId(String duplicateAnalyzerResultId) { - this.duplicateAnalyzerResultId = duplicateAnalyzerResultId; - } - - public String getDuplicateAnalyzerResultId() { - return duplicateAnalyzerResultId; - } - - public void setReadOnly(boolean isReadOnly) { - this.isReadOnly = isReadOnly; - } - - public boolean isReadOnly() { - return isReadOnly; - } - - public void setTestId(String testId) { - this.testId = testId; - } - - public String getTestId() { - return testId; - } - - public void setResultType(String resultType) { - this.resultType = resultType; - } + private static final long serialVersionUID = 1L; + + private String id; + private String analyzerId; + private String accessionNumber; + private String testName; + private String result; + private String units; + private String duplicateAnalyzerResultId; + private boolean isControl = false; + private boolean isReadOnly = false; + private String testId; + private String resultType = "N"; + private Timestamp completeDate; + + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return this.id; + } + + public void setAnalyzerId(String analyzerId) { + this.analyzerId = analyzerId; + } + + public String getAnalyzerId() { + return analyzerId; + } + + public void setAccessionNumber(String accessionNumber) { + this.accessionNumber = accessionNumber.replaceAll("\'", ""); + } + + public String getAccessionNumber() { + return accessionNumber; + } + + public void setTestName(String testName) { + this.testName = testName; + } + + public String getTestName() { + return testName; + } + + public void setResult(String result) { + this.result = result; + } + + public String getResult() { + return this.result; + } + + public void setUnits(String units) { + this.units = units; + } + + public String getUnits() { + return units; + } + + public void setIsControl(boolean isControl) { + this.isControl = isControl; + } + + public boolean getIsControl() { + return isControl; + } + + public void setCompleteDate(Timestamp completeDate) { + this.completeDate = completeDate; + } + + public Timestamp getCompleteDate() { + return completeDate; + } + + public String getCompleteDateForDisplay() { + return DateUtil.convertTimestampToStringDate(completeDate); + } + + public void setDuplicateAnalyzerResultId(String duplicateAnalyzerResultId) { + this.duplicateAnalyzerResultId = duplicateAnalyzerResultId; + } + + public String getDuplicateAnalyzerResultId() { + return duplicateAnalyzerResultId; + } + + public void setReadOnly(boolean isReadOnly) { + this.isReadOnly = isReadOnly; + } + + public boolean isReadOnly() { + return isReadOnly; + } + + public void setTestId(String testId) { + this.testId = testId; + } + + public String getTestId() { + return testId; + } + + public void setResultType(String resultType) { + this.resultType = resultType; + } - public String getResultType() { - return resultType; - } + public String getResultType() { + return resultType; + } } diff --git a/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailItem.java b/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailItem.java index 9eb956019a..9cdc89c950 100644 --- a/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailItem.java +++ b/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailItem.java @@ -18,117 +18,117 @@ public class AuditTrailItem implements Serializable { - private static final long serialVersionUID = 6253410461743508243L; - private Timestamp timeStamp; - private String date; - private String time; - private String action; - private String user; - private String item; - private String attribute = ""; - private String newValue = ""; - private String oldValue = ""; - private String identifier = ""; - private String className = ""; - private String referencedId; - - public Timestamp getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(Timestamp timeStamp) { - this.timeStamp = timeStamp; - } - - public String getDate() { - return date; - } - - public void setDate(String date) { - this.date = date; - } - - public String getTime() { - return time; - } - - public void setTime(String time) { - this.time = time; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getItem() { - return item; - } - - public void setItem(String item) { - this.item = item; - } - - public String getAttribute() { - return attribute; - } - - public void setAttribute(String attribute) { - this.attribute = attribute; - } - - public String getNewValue() { - return newValue; - } - - public void setNewValue(String value) { - this.newValue = value; - } - - public String getOldValue() { - return oldValue; - } - - public void setOldValue(String oldValue) { - this.oldValue = oldValue; - } - - public String getIdentifier() { - return identifier; - } - - public void setIdentifier(String identifier) { - this.identifier = identifier; - } - - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public boolean newOldDiffer() { - return newValue == null ? true : !newValue.equals(oldValue); - } - - public String getReferencedId() { - return referencedId; - } - - public void setReferencedId(String referencedId) { - this.referencedId = referencedId; - } + private static final long serialVersionUID = 6253410461743508243L; + private Timestamp timeStamp; + private String date; + private String time; + private String action; + private String user; + private String item; + private String attribute = ""; + private String newValue = ""; + private String oldValue = ""; + private String identifier = ""; + private String className = ""; + private String referencedId; + + public Timestamp getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(Timestamp timeStamp) { + this.timeStamp = timeStamp; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getItem() { + return item; + } + + public void setItem(String item) { + this.item = item; + } + + public String getAttribute() { + return attribute; + } + + public void setAttribute(String attribute) { + this.attribute = attribute; + } + + public String getNewValue() { + return newValue; + } + + public void setNewValue(String value) { + this.newValue = value; + } + + public String getOldValue() { + return oldValue; + } + + public void setOldValue(String oldValue) { + this.oldValue = oldValue; + } + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public boolean newOldDiffer() { + return newValue == null ? true : !newValue.equals(oldValue); + } + + public String getReferencedId() { + return referencedId; + } + + public void setReferencedId(String referencedId) { + this.referencedId = referencedId; + } } diff --git a/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailViewWorker.java b/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailViewWorker.java index 3842b4c026..55377a9072 100644 --- a/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailViewWorker.java +++ b/src/main/java/org/openelisglobal/audittrail/action/workers/AuditTrailViewWorker.java @@ -47,258 +47,254 @@ public class AuditTrailViewWorker { - protected AnalysisService analysisService = SpringContext.getBean(AnalysisService.class); - protected ResultService resultService = SpringContext.getBean(ResultService.class); - protected SampleService sampleService = SpringContext.getBean(SampleService.class); + protected AnalysisService analysisService = SpringContext.getBean(AnalysisService.class); + protected ResultService resultService = SpringContext.getBean(ResultService.class); + protected SampleService sampleService = SpringContext.getBean(SampleService.class); - private String accessionNumber = null; - private Sample sample; + private String accessionNumber = null; + private Sample sample; - public AuditTrailViewWorker(String accessionNumber) { - this.accessionNumber = accessionNumber; - sample = null; - } - - public List getAuditTrail() throws IllegalStateException { - if (GenericValidator.isBlankOrNull(accessionNumber)) { - throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + public AuditTrailViewWorker(String accessionNumber) { + this.accessionNumber = accessionNumber; + sample = null; } - getSample(); + public List getAuditTrail() throws IllegalStateException { + if (GenericValidator.isBlankOrNull(accessionNumber)) { + throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + } - List items = new ArrayList<>(); + getSample(); - if (sample != null) { - items.addAll(addOrders()); - items.addAll(addSamples()); - items.addAll(addTestsAndResults()); - items.addAll(addReports()); - items.addAll(addPatientHistory()); - items.addAll(addNotes()); - items.addAll(addQAEvents()); - } + List items = new ArrayList<>(); - sortItemsByTime(items); - return items; - } + if (sample != null) { + items.addAll(addOrders()); + items.addAll(addSamples()); + items.addAll(addTestsAndResults()); + items.addAll(addReports()); + items.addAll(addPatientHistory()); + items.addAll(addNotes()); + items.addAll(addQAEvents()); + } - public SampleOrderItem getSampleOrderSnapshot() { - if (GenericValidator.isBlankOrNull(accessionNumber)) { - throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + sortItemsByTime(items); + return items; } - SampleOrderService orderService = new SampleOrderService(accessionNumber, true); - return orderService.getSampleOrderItem(); - } + public SampleOrderItem getSampleOrderSnapshot() { + if (GenericValidator.isBlankOrNull(accessionNumber)) { + throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + } - public PatientManagementInfo getPatientSnapshot() { - if (GenericValidator.isBlankOrNull(accessionNumber)) { - throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + SampleOrderService orderService = new SampleOrderService(accessionNumber, true); + return orderService.getSampleOrderItem(); } - getSample(); + public PatientManagementInfo getPatientSnapshot() { + if (GenericValidator.isBlankOrNull(accessionNumber)) { + throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + } - if (sample != null) { - SampleHumanService sampleHumanService = SpringContext.getBean(SampleHumanService.class); - Patient patient = sampleHumanService.getPatientForSample(sample); - return new PatientManagementBridge().getPatientManagementInfoFor(patient, true); - } else { - return new PatientManagementInfo(); - } - } + getSample(); - public List getPatientHistoryAuditTrail() throws IllegalStateException { - if (GenericValidator.isBlankOrNull(accessionNumber)) { - throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + if (sample != null) { + SampleHumanService sampleHumanService = SpringContext.getBean(SampleHumanService.class); + Patient patient = sampleHumanService.getPatientForSample(sample); + return new PatientManagementBridge().getPatientManagementInfoFor(patient, true); + } else { + return new PatientManagementInfo(); + } } - getSample(); + public List getPatientHistoryAuditTrail() throws IllegalStateException { + if (GenericValidator.isBlankOrNull(accessionNumber)) { + throw new IllegalStateException("AuditTrialViewWorker is not initialized"); + } - List items = new ArrayList<>(); + getSample(); - if (sample != null) { - items.addAll(addPatientHistory()); + List items = new ArrayList<>(); + + if (sample != null) { + items.addAll(addPatientHistory()); + } + return items; } - return items; - } - private void getSample() { - if (sample == null) { - sample = sampleService.getSampleByAccessionNumber(accessionNumber); + private void getSample() { + if (sample == null) { + sample = sampleService.getSampleByAccessionNumber(accessionNumber); + } } - } - private Collection addReports() { - List items = new ArrayList<>(); + private Collection addReports() { + List items = new ArrayList<>(); - if (sample != null) { - AbstractHistoryService historyService = new ReportHistoryService(sample); - items.addAll(historyService.getAuditTrailItems()); + if (sample != null) { + AbstractHistoryService historyService = new ReportHistoryService(sample); + items.addAll(historyService.getAuditTrailItems()); - // sortItemsByTime(items); - } + // sortItemsByTime(items); + } - for (AuditTrailItem auditTrailItem : items) { - auditTrailItem.setClassName("reportAudit"); - setAttributeNewIfInsert(auditTrailItem); + for (AuditTrailItem auditTrailItem : items) { + auditTrailItem.setClassName("reportAudit"); + setAttributeNewIfInsert(auditTrailItem); + } + return items; } - return items; - } - private Collection addSamples() { - List sampleItems = new ArrayList<>(); - if (sample != null) { - AbstractHistoryService historyService = new SampleHistoryService(sample); - sampleItems.addAll(historyService.getAuditTrailItems()); + private Collection addSamples() { + List sampleItems = new ArrayList<>(); + if (sample != null) { + AbstractHistoryService historyService = new SampleHistoryService(sample); + sampleItems.addAll(historyService.getAuditTrailItems()); - // sortItems(sampleItems); + // sortItems(sampleItems); - for (AuditTrailItem auditTrailItem : sampleItems) { - auditTrailItem.setClassName("sampleAudit"); - setAttributeNewIfInsert(auditTrailItem); - } + for (AuditTrailItem auditTrailItem : sampleItems) { + auditTrailItem.setClassName("sampleAudit"); + setAttributeNewIfInsert(auditTrailItem); + } + } + + return sampleItems; } - return sampleItems; - } + private Collection addOrders() { + List orderItems = new ArrayList<>(); + if (sample != null) { + AbstractHistoryService historyService = new OrderHistoryService(sample); + orderItems.addAll(historyService.getAuditTrailItems()); - private Collection addOrders() { - List orderItems = new ArrayList<>(); - if (sample != null) { - AbstractHistoryService historyService = new OrderHistoryService(sample); - orderItems.addAll(historyService.getAuditTrailItems()); + // sortItems(orderItems); - // sortItems(orderItems); + for (AuditTrailItem auditTrailItem : orderItems) { + auditTrailItem.setClassName("orderAudit"); + setAttributeNewIfInsert(auditTrailItem); + } + } - for (AuditTrailItem auditTrailItem : orderItems) { - auditTrailItem.setClassName("orderAudit"); - setAttributeNewIfInsert(auditTrailItem); - } + return orderItems; } - return orderItems; - } - - private void setAttributeNewIfInsert(AuditTrailItem auditTrailItem) { - if (auditTrailItem.getAction().equals("I")) { - auditTrailItem.setAttribute(MessageUtil.getMessage("auditTrail.action.new")); + private void setAttributeNewIfInsert(AuditTrailItem auditTrailItem) { + if (auditTrailItem.getAction().equals("I")) { + auditTrailItem.setAttribute(MessageUtil.getMessage("auditTrail.action.new")); + } } - } - private List addTestsAndResults() { - List items = new ArrayList<>(); + private List addTestsAndResults() { + List items = new ArrayList<>(); - List analysisList = analysisService.getAnalysesBySampleId(sample.getId()); + List analysisList = analysisService.getAnalysesBySampleId(sample.getId()); - for (Analysis analysis : analysisList) { - List resultList = resultService.getResultsByAnalysis(analysis); - AbstractHistoryService historyService = new AnalysisHistoryService(analysis); - List resultItems = historyService.getAuditTrailItems(); - items.addAll(resultItems); + for (Analysis analysis : analysisList) { + List resultList = resultService.getResultsByAnalysis(analysis); + AbstractHistoryService historyService = new AnalysisHistoryService(analysis); + List resultItems = historyService.getAuditTrailItems(); + items.addAll(resultItems); - for (Result result : resultList) { - historyService = new ResultHistoryService(result, analysis); - resultItems = historyService.getAuditTrailItems(); + for (Result result : resultList) { + historyService = new ResultHistoryService(result, analysis); + resultItems = historyService.getAuditTrailItems(); - items.addAll(resultItems); - } + items.addAll(resultItems); + } + } + + // sortItems(items); + for (AuditTrailItem auditTrailItem : items) { + auditTrailItem.setClassName("testResultAudit"); + setAttributeNewIfInsert(auditTrailItem); + } + return items; } - // sortItems(items); - for (AuditTrailItem auditTrailItem : items) { - auditTrailItem.setClassName("testResultAudit"); - setAttributeNewIfInsert(auditTrailItem); - } - return items; - } - - private Collection addPatientHistory() { - List items = new ArrayList<>(); - AbstractHistoryService historyService; - Patient patient = PatientUtil.getPatientForSample(sample); - if (patient != null) { - historyService = new PatientHistoryService(patient); - items.addAll(historyService.getAuditTrailItems()); - } + private Collection addPatientHistory() { + List items = new ArrayList<>(); + AbstractHistoryService historyService; + Patient patient = PatientUtil.getPatientForSample(sample); + if (patient != null) { + historyService = new PatientHistoryService(patient); + items.addAll(historyService.getAuditTrailItems()); + } + + // historyService = new HistoryService(sample, HistoryType.PERSON); + // items.addAll(historyService.getAuditTrailItems()); - // historyService = new HistoryService(sample, HistoryType.PERSON); - // items.addAll(historyService.getAuditTrailItems()); + historyService = new PatientHistoryHistoryService(sample); + items.addAll(historyService.getAuditTrailItems()); - historyService = new PatientHistoryHistoryService(sample); - items.addAll(historyService.getAuditTrailItems()); + // sortItems(items); - // sortItems(items); + for (AuditTrailItem auditTrailItem : items) { + auditTrailItem.setClassName("patientHistoryAudit"); + setAttributeNewIfInsert(auditTrailItem); + } - for (AuditTrailItem auditTrailItem : items) { - auditTrailItem.setClassName("patientHistoryAudit"); - setAttributeNewIfInsert(auditTrailItem); + return items; } - return items; - } + private Collection addNotes() { + List notes = new ArrayList<>(); + if (sample != null) { + AbstractHistoryService historyService = new NoteHistoryService(sample); + notes.addAll(historyService.getAuditTrailItems()); - private Collection addNotes() { - List notes = new ArrayList<>(); - if (sample != null) { - AbstractHistoryService historyService = new NoteHistoryService(sample); - notes.addAll(historyService.getAuditTrailItems()); + // sortItems(notes); - // sortItems(notes); + for (AuditTrailItem auditTrailItem : notes) { + auditTrailItem.setClassName("noteAudit"); + setAttributeNewIfInsert(auditTrailItem); + } + } - for (AuditTrailItem auditTrailItem : notes) { - auditTrailItem.setClassName("noteAudit"); - setAttributeNewIfInsert(auditTrailItem); - } + return notes; } - return notes; - } + private Collection addQAEvents() { + List qaEvents = new ArrayList<>(); + if (sample != null) { + QaHistoryService qaService = new QaHistoryService(sample); + qaEvents = qaService.getAuditTrailItems(); - private Collection addQAEvents() { - List qaEvents = new ArrayList<>(); - if (sample != null) { - QaHistoryService qaService = new QaHistoryService(sample); - qaEvents = qaService.getAuditTrailItems(); + for (AuditTrailItem auditTrailItem : qaEvents) { + auditTrailItem.setClassName("qaEvent"); + setAttributeNewIfInsert(auditTrailItem); + } + } - for (AuditTrailItem auditTrailItem : qaEvents) { - auditTrailItem.setClassName("qaEvent"); - setAttributeNewIfInsert(auditTrailItem); - } + return qaEvents; } - return qaEvents; - } - - @SuppressWarnings("unused") - private void sortItems(List items) { - Collections.sort( - items, - new Comparator() { - @Override - public int compare(AuditTrailItem o1, AuditTrailItem o2) { - int sort = o1.getIdentifier().compareTo(o2.getIdentifier()); - if (sort != 0) { - return sort; + @SuppressWarnings("unused") + private void sortItems(List items) { + Collections.sort(items, new Comparator() { + @Override + public int compare(AuditTrailItem o1, AuditTrailItem o2) { + int sort = o1.getIdentifier().compareTo(o2.getIdentifier()); + if (sort != 0) { + return sort; + } + + sort = o1.getTimeStamp().compareTo(o2.getTimeStamp()); + if (sort != 0) { + return sort; + } + + return o1.getAction().compareTo(o2.getAction()); } + }); + } - sort = o1.getTimeStamp().compareTo(o2.getTimeStamp()); - if (sort != 0) { - return sort; + private void sortItemsByTime(List items) { + Collections.sort(items, new Comparator() { + @Override + public int compare(AuditTrailItem o1, AuditTrailItem o2) { + return o1.getTimeStamp().compareTo(o2.getTimeStamp()); } - - return o1.getAction().compareTo(o2.getAction()); - } }); - } - - private void sortItemsByTime(List items) { - Collections.sort( - items, - new Comparator() { - @Override - public int compare(AuditTrailItem o1, AuditTrailItem o2) { - return o1.getTimeStamp().compareTo(o2.getTimeStamp()); - } - }); - } + } } diff --git a/src/main/java/org/openelisglobal/audittrail/controller/AuditTrailReportController.java b/src/main/java/org/openelisglobal/audittrail/controller/AuditTrailReportController.java index 5089fabb3f..c0b23a86c1 100644 --- a/src/main/java/org/openelisglobal/audittrail/controller/AuditTrailReportController.java +++ b/src/main/java/org/openelisglobal/audittrail/controller/AuditTrailReportController.java @@ -20,48 +20,48 @@ @Controller public class AuditTrailReportController extends BaseController { - private static final String[] ALLOWED_FIELDS = new String[] {"accessionNumberSearch"}; + private static final String[] ALLOWED_FIELDS = new String[] { "accessionNumberSearch" }; - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.setAllowedFields(ALLOWED_FIELDS); - } + @InitBinder + public void initBinder(WebDataBinder binder) { + binder.setAllowedFields(ALLOWED_FIELDS); + } - @RequestMapping(value = "/AuditTrailReport", method = RequestMethod.GET) - public ModelAndView showAuditTrailReport( - HttpServletRequest request, @ModelAttribute("form") @Valid AuditTrailViewForm form) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { - form.setFormMethod(RequestMethod.GET); + @RequestMapping(value = "/AuditTrailReport", method = RequestMethod.GET) + public ModelAndView showAuditTrailReport(HttpServletRequest request, + @ModelAttribute("form") @Valid AuditTrailViewForm form) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { + form.setFormMethod(RequestMethod.GET); - String accessionNumber = form.getAccessionNumberSearch(); - if (!GenericValidator.isBlankOrNull(accessionNumber)) { - AuditTrailViewWorker worker = new AuditTrailViewWorker(accessionNumber); - List items = worker.getAuditTrail(); - form.setLog(items); - form.setAccessionNumber(accessionNumber); - form.setSampleOrderItems(worker.getSampleOrderSnapshot()); - form.setPatientProperties(worker.getPatientSnapshot()); - } + String accessionNumber = form.getAccessionNumberSearch(); + if (!GenericValidator.isBlankOrNull(accessionNumber)) { + AuditTrailViewWorker worker = new AuditTrailViewWorker(accessionNumber); + List items = worker.getAuditTrail(); + form.setLog(items); + form.setAccessionNumber(accessionNumber); + form.setSampleOrderItems(worker.getSampleOrderSnapshot()); + form.setPatientProperties(worker.getPatientSnapshot()); + } - return findForward(FWD_SUCCESS, form); - } + return findForward(FWD_SUCCESS, form); + } - @Override - protected String findLocalForward(String forward) { - if (FWD_SUCCESS.equals(forward)) { - return "auditTrailViewDefinition"; - } else { - return "PageNotFound"; + @Override + protected String findLocalForward(String forward) { + if (FWD_SUCCESS.equals(forward)) { + return "auditTrailViewDefinition"; + } else { + return "PageNotFound"; + } } - } - @Override - protected String getPageTitleKey() { - return "reports.auditTrail"; - } + @Override + protected String getPageTitleKey() { + return "reports.auditTrail"; + } - @Override - protected String getPageSubtitleKey() { - return "reports.auditTrail"; - } + @Override + protected String getPageSubtitleKey() { + return "reports.auditTrail"; + } } diff --git a/src/main/java/org/openelisglobal/audittrail/controller/rest/AuditTrailReportRestController.java b/src/main/java/org/openelisglobal/audittrail/controller/rest/AuditTrailReportRestController.java index aff88215a2..a6263e6927 100644 --- a/src/main/java/org/openelisglobal/audittrail/controller/rest/AuditTrailReportRestController.java +++ b/src/main/java/org/openelisglobal/audittrail/controller/rest/AuditTrailReportRestController.java @@ -12,23 +12,22 @@ @RestController public class AuditTrailReportRestController { - @GetMapping("/rest/AuditTrailReport") - public ResponseEntity getAuditTrailReport( - @RequestParam String accessionNumber) { - AuditTrailViewForm response = new AuditTrailViewForm(); - AuditTrailViewWorker worker = new AuditTrailViewWorker(accessionNumber); - List items = worker.getAuditTrail(); + @GetMapping("/rest/AuditTrailReport") + public ResponseEntity getAuditTrailReport(@RequestParam String accessionNumber) { + AuditTrailViewForm response = new AuditTrailViewForm(); + AuditTrailViewWorker worker = new AuditTrailViewWorker(accessionNumber); + List items = worker.getAuditTrail(); - if (items.size() == 0) { - // Set error message if accession number is not found - return ResponseEntity.ok(response); - } + if (items.size() == 0) { + // Set error message if accession number is not found + return ResponseEntity.ok(response); + } - // Populate the response object - response.setAccessionNumber(accessionNumber); - response.setLog(items); - response.setSampleOrderItems(worker.getSampleOrderSnapshot()); - response.setPatientProperties(worker.getPatientSnapshot()); - return ResponseEntity.ok(response); - } + // Populate the response object + response.setAccessionNumber(accessionNumber); + response.setLog(items); + response.setSampleOrderItems(worker.getSampleOrderSnapshot()); + response.setPatientProperties(worker.getPatientSnapshot()); + return ResponseEntity.ok(response); + } } diff --git a/src/main/java/org/openelisglobal/audittrail/dao/AuditTrailService.java b/src/main/java/org/openelisglobal/audittrail/dao/AuditTrailService.java index e73733c52d..ab05862391 100644 --- a/src/main/java/org/openelisglobal/audittrail/dao/AuditTrailService.java +++ b/src/main/java/org/openelisglobal/audittrail/dao/AuditTrailService.java @@ -22,33 +22,27 @@ */ public interface AuditTrailService { - void saveHistory( - BaseObject newObject, - BaseObject existingObject, - String sysUserId, - String event, - String tableName) - throws LIMSRuntimeException; + void saveHistory(BaseObject newObject, BaseObject existingObject, String sysUserId, String event, String tableName) + throws LIMSRuntimeException; - void saveNewHistory(BaseObject newObject, String sysUserId, String tableName) - throws LIMSRuntimeException; + void saveNewHistory(BaseObject newObject, String sysUserId, String tableName) throws LIMSRuntimeException; - String getXML(String table, String id) throws LIMSRuntimeException; + String getXML(String table, String id) throws LIMSRuntimeException; - String getXMLData(String table, String id) throws LIMSRuntimeException; + String getXMLData(String table, String id) throws LIMSRuntimeException; - // public List getHistoryByRefIdAndRefTableId(History history) throws - // LIMSRuntimeException; + // public List getHistoryByRefIdAndRefTableId(History history) throws + // LIMSRuntimeException; - // public List getHistoryByRefIdAndRefTableId(String refId, String tableId) - // throws LIMSRuntimeException; + // public List getHistoryByRefIdAndRefTableId(String refId, String tableId) + // throws LIMSRuntimeException; - // public List getHistoryBySystemUserAndDateAndRefTableId(History history) - // throws LIMSRuntimeException; + // public List getHistoryBySystemUserAndDateAndRefTableId(History history) + // throws LIMSRuntimeException; - // public String retrieveBlobData(String id) throws LIMSRuntimeException; + // public String retrieveBlobData(String id) throws LIMSRuntimeException; - // public List getHistoryByRefTableIdAndDateRange(String - // referenceTableId, Date start, Date end) - // throws LIMSRuntimeException; + // public List getHistoryByRefTableIdAndDateRange(String + // referenceTableId, Date start, Date end) + // throws LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/audittrail/dao/HistoryDAO.java b/src/main/java/org/openelisglobal/audittrail/dao/HistoryDAO.java index c4fc01e507..c44834f165 100644 --- a/src/main/java/org/openelisglobal/audittrail/dao/HistoryDAO.java +++ b/src/main/java/org/openelisglobal/audittrail/dao/HistoryDAO.java @@ -7,7 +7,7 @@ public interface HistoryDAO extends BaseDAO { - List getHistoryByRefIdAndRefTableId(String Id, String Table) throws LIMSRuntimeException; + List getHistoryByRefIdAndRefTableId(String Id, String Table) throws LIMSRuntimeException; - List getHistoryByRefIdAndRefTableId(History history) throws LIMSRuntimeException; + List getHistoryByRefIdAndRefTableId(History history) throws LIMSRuntimeException; } diff --git a/src/main/java/org/openelisglobal/audittrail/daoimpl/AuditTrailServiceImpl.java b/src/main/java/org/openelisglobal/audittrail/daoimpl/AuditTrailServiceImpl.java index 70ef2afe22..73a72d0d1b 100644 --- a/src/main/java/org/openelisglobal/audittrail/daoimpl/AuditTrailServiceImpl.java +++ b/src/main/java/org/openelisglobal/audittrail/daoimpl/AuditTrailServiceImpl.java @@ -38,1282 +38,1249 @@ @Transactional public class AuditTrailServiceImpl implements AuditTrailService { - @Autowired private ReferenceTablesService referenceTablesService; - - @Autowired private HistoryService historyService; - - // For an insert log the id, sys_user_id, ref id, reftable, timestamp, activity - // (='I'). The change column would be blank, since the - // before data did not contain anything. Note: This requires making the changes - // column (in history table) nullable - @Override - public void saveNewHistory(BaseObject newObject, String sysUserId, String tableName) - throws LIMSRuntimeException { - - ReferenceTables referenceTables = new ReferenceTables(); - referenceTables.setTableName(tableName); - ReferenceTables referenceTable = - referenceTablesService.getReferenceTableByName(referenceTables); - - // bugzilla 2111: if keepHistory is N then return - don't throw exception - if (referenceTable != null && !referenceTable.getKeepHistory().equals(IActionConstants.YES)) { - LogEvent.logDebug( - "AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: REF TABLE KEEP_HISTORY IS N"); - return; - } - // if logging failes an exception should be thrown so that INSERT/UPDATE is - // rolled back - if (referenceTable == null) { - LogEvent.logError("AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: REF TABLE IS NULL"); - throw new LIMSRuntimeException( - "Reference Table is null in AuditTrailDAOImpl saveNewHistory()"); - } - - if ((sysUserId == null) || (sysUserId.length() == 0)) { - LogEvent.logError("AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: SYS_USER_ID IS NULL"); - throw new LIMSRuntimeException( - "System User ID is null in AuditTrailDAOImpl saveNewHistory()"); - } - - if (newObject == null || tableName == null) { - LogEvent.logError( - "AuditTrailDAOImpl", - "saveNewHistory()", - "NO CHANGES: EITHER OBJECT or TABLE NAME IS NULL"); - throw new LIMSRuntimeException( - "Either new object or table name is null in AuditTrailDAOImpl saveNewHistory()"); - } + @Autowired + private ReferenceTablesService referenceTablesService; + + @Autowired + private HistoryService historyService; + + // For an insert log the id, sys_user_id, ref id, reftable, timestamp, activity + // (='I'). The change column would be blank, since the + // before data did not contain anything. Note: This requires making the changes + // column (in history table) nullable + @Override + public void saveNewHistory(BaseObject newObject, String sysUserId, String tableName) throws LIMSRuntimeException { + + ReferenceTables referenceTables = new ReferenceTables(); + referenceTables.setTableName(tableName); + ReferenceTables referenceTable = referenceTablesService.getReferenceTableByName(referenceTables); + + // bugzilla 2111: if keepHistory is N then return - don't throw exception + if (referenceTable != null && !referenceTable.getKeepHistory().equals(IActionConstants.YES)) { + LogEvent.logDebug("AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: REF TABLE KEEP_HISTORY IS N"); + return; + } + // if logging failes an exception should be thrown so that INSERT/UPDATE is + // rolled back + if (referenceTable == null) { + LogEvent.logError("AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: REF TABLE IS NULL"); + throw new LIMSRuntimeException("Reference Table is null in AuditTrailDAOImpl saveNewHistory()"); + } - History hist = new History(); - - try { - String referenceId = newObject.getStringId(); - hist.setReferenceId(referenceId); - hist.setSysUserId(sysUserId); - - Timestamp timestamp = newObject.getLastupdated(); - if (timestamp == null) { - timestamp = new Timestamp(System.currentTimeMillis()); - } - - hist.setTimestamp(timestamp); - hist.setActivity(IActionConstants.AUDIT_TRAIL_INSERT); - hist.setReferenceTable(referenceTable.getId()); - insertData(hist); - } catch (RuntimeException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error occurred logging INSERT", e); - } - } - - @Override - public void saveHistory( - BaseObject newObject, - BaseObject existingObject, - String sysUserId, - String event, - String tableName) - throws LIMSRuntimeException { - - // bugzilla 2571 go through ReferenceTablesDAO to get reference tables info - ReferenceTables referenceTables = new ReferenceTables(); - referenceTables.setTableName(tableName); - ReferenceTables rt = referenceTablesService.getReferenceTableByName(referenceTables); - - // bugzilla 2111: if keepHistory is N then return - don't throw exception - if (rt != null && !rt.getKeepHistory().equals(IActionConstants.YES)) { - // bugzilla 2154 - LogEvent.logDebug( - "AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: REF TABLE KEEP_HISTORY IS N"); - return; - } - if (rt == null) { - // bugzilla 2154 - LogEvent.logError("AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: REF TABLE IS NULL"); - // bugzilla 1926 - throw new LIMSRuntimeException("Reference Table is null in AuditTrailDAOImpl saveHistory()"); - } + if ((sysUserId == null) || (sysUserId.length() == 0)) { + LogEvent.logError("AuditTrailDAOImpl", "saveNewHistory()", "NO CHANGES: SYS_USER_ID IS NULL"); + throw new LIMSRuntimeException("System User ID is null in AuditTrailDAOImpl saveNewHistory()"); + } - if ((sysUserId == null) || (sysUserId.length() == 0)) { - // bugzilla 2154 - LogEvent.logError("AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: SYS_USER_ID IS NULL"); - // bugzilla 1926 - throw new LIMSRuntimeException( - "System User ID is null in AuditTrailDAOImpl saveHistory() for table " + tableName); - } + if (newObject == null || tableName == null) { + LogEvent.logError("AuditTrailDAOImpl", "saveNewHistory()", + "NO CHANGES: EITHER OBJECT or TABLE NAME IS NULL"); + throw new LIMSRuntimeException( + "Either new object or table name is null in AuditTrailDAOImpl saveNewHistory()"); + } - if ((newObject == null && IActionConstants.AUDIT_TRAIL_UPDATE.equals(event)) - || existingObject == null - || event == null - || tableName == null) { - // bugzilla 2154 - LogEvent.logError( - "AuditTrailDAOImpl", - "saveHistory()", - "NO CHANGES: EITHER OBJECTS or EVENT or TABLE NAME IS NULL"); - // bugzilla 1926 - throw new LIMSRuntimeException( - "New object, existing object, table name or event is null in AuditTrailDAOImpl" - + " saveHistory()"); - } + History hist = new History(); - try { - String xml = getChanges(newObject, existingObject, tableName); + try { + String referenceId = newObject.getStringId(); + hist.setReferenceId(referenceId); + hist.setSysUserId(sysUserId); - if ((xml != null) && (xml.length() > 0)) { - History hist = new History(); + Timestamp timestamp = newObject.getLastupdated(); + if (timestamp == null) { + timestamp = new Timestamp(System.currentTimeMillis()); + } - String referenceId = null; - if (newObject != null && event.equals(IActionConstants.AUDIT_TRAIL_UPDATE)) { - referenceId = newObject.getStringId(); - } else if (event.equals(IActionConstants.AUDIT_TRAIL_DELETE)) { - referenceId = existingObject.getStringId(); + hist.setTimestamp(timestamp); + hist.setActivity(IActionConstants.AUDIT_TRAIL_INSERT); + hist.setReferenceTable(referenceTable.getId()); + insertData(hist); + } catch (RuntimeException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error occurred logging INSERT", e); } - hist.setReferenceId(referenceId); - hist.setSysUserId(sysUserId); - - byte[] bytes = xml.getBytes(); - hist.setChanges(bytes); - - // Method m3 = existingObject.getClass().getMethod("getLastupdated", new - // Class[0]); - // java.sql.Timestamp ts = (java.sql.Timestamp)m3.invoke(existingObject, - // (Object[])new Class[0]); - // if ( ts == null ) - // bugzilla 2574 - java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis()); - - hist.setTimestamp(ts); - hist.setActivity(event); - hist.setReferenceTable(rt.getId()); - insertData(hist); - } - } catch (RuntimeException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail saveHistory()", e); } - } - - /** - * Returns an array of all fields used by this object from it's class and all superclasses. - * - * @param objectClass the class - * @param fields the current field list - * @return an array of fields - */ - private Field[] getAllFields(Class objectClass, Field[] fields) { - Field[] newFields = objectClass.getDeclaredFields(); + @Override + public void saveHistory(BaseObject newObject, BaseObject existingObject, String sysUserId, String event, + String tableName) throws LIMSRuntimeException { - int fieldsSize = 0; - int newFieldsSize = 0; + // bugzilla 2571 go through ReferenceTablesDAO to get reference tables info + ReferenceTables referenceTables = new ReferenceTables(); + referenceTables.setTableName(tableName); + ReferenceTables rt = referenceTablesService.getReferenceTableByName(referenceTables); - if (fields != null) { - fieldsSize = fields.length; - } + // bugzilla 2111: if keepHistory is N then return - don't throw exception + if (rt != null && !rt.getKeepHistory().equals(IActionConstants.YES)) { + // bugzilla 2154 + LogEvent.logDebug("AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: REF TABLE KEEP_HISTORY IS N"); + return; + } + if (rt == null) { + // bugzilla 2154 + LogEvent.logError("AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: REF TABLE IS NULL"); + // bugzilla 1926 + throw new LIMSRuntimeException("Reference Table is null in AuditTrailDAOImpl saveHistory()"); + } - if (newFields != null) { - newFieldsSize = newFields.length; - } + if ((sysUserId == null) || (sysUserId.length() == 0)) { + // bugzilla 2154 + LogEvent.logError("AuditTrailDAOImpl", "saveHistory()", "NO CHANGES: SYS_USER_ID IS NULL"); + // bugzilla 1926 + throw new LIMSRuntimeException( + "System User ID is null in AuditTrailDAOImpl saveHistory() for table " + tableName); + } - Field[] totalFields = new Field[fieldsSize + newFieldsSize]; + if ((newObject == null && IActionConstants.AUDIT_TRAIL_UPDATE.equals(event)) || existingObject == null + || event == null || tableName == null) { + // bugzilla 2154 + LogEvent.logError("AuditTrailDAOImpl", "saveHistory()", + "NO CHANGES: EITHER OBJECTS or EVENT or TABLE NAME IS NULL"); + // bugzilla 1926 + throw new LIMSRuntimeException( + "New object, existing object, table name or event is null in AuditTrailDAOImpl" + " saveHistory()"); + } - if (fieldsSize > 0) { - System.arraycopy(fields, 0, totalFields, 0, fieldsSize); + try { + String xml = getChanges(newObject, existingObject, tableName); + + if ((xml != null) && (xml.length() > 0)) { + History hist = new History(); + + String referenceId = null; + if (newObject != null && event.equals(IActionConstants.AUDIT_TRAIL_UPDATE)) { + referenceId = newObject.getStringId(); + } else if (event.equals(IActionConstants.AUDIT_TRAIL_DELETE)) { + referenceId = existingObject.getStringId(); + } + hist.setReferenceId(referenceId); + hist.setSysUserId(sysUserId); + + byte[] bytes = xml.getBytes(); + hist.setChanges(bytes); + + // Method m3 = existingObject.getClass().getMethod("getLastupdated", new + // Class[0]); + // java.sql.Timestamp ts = (java.sql.Timestamp)m3.invoke(existingObject, + // (Object[])new Class[0]); + // if ( ts == null ) + // bugzilla 2574 + java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis()); + + hist.setTimestamp(ts); + hist.setActivity(event); + hist.setReferenceTable(rt.getId()); + insertData(hist); + } + } catch (RuntimeException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail saveHistory()", e); + } } - if (newFieldsSize > 0) { - System.arraycopy(newFields, 0, totalFields, fieldsSize, newFieldsSize); - } + /** + * Returns an array of all fields used by this object from it's class and all + * superclasses. + * + * @param objectClass the class + * @param fields the current field list + * @return an array of fields + */ + private Field[] getAllFields(Class objectClass, Field[] fields) { - Class superClass = objectClass.getSuperclass(); + Field[] newFields = objectClass.getDeclaredFields(); - Field[] finalFieldsArray; + int fieldsSize = 0; + int newFieldsSize = 0; - if (superClass != null && !superClass.equals(Object.class)) { - finalFieldsArray = getAllFields(superClass, totalFields); - } else { - finalFieldsArray = totalFields; - } + if (fields != null) { + fieldsSize = fields.length; + } - return finalFieldsArray; - } - - /** - * Logs changes to persistent data - * - * @param newObject the object being saved, updated or deleted - * @param existingObject the existing object in the database. Used only for updates - * @param tableName the name of the table being logged. - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @throws InvocationTargetException - */ - private String getChanges(BaseObject newObject, BaseObject existingObject, String tableName) { - - // bugzilla 1857 - Vector optionList = new Vector<>(); - Class objectClass = existingObject.getClass(); - // get an array of all fields in the class including those in superclasses if - // this is a subclass. - Field[] fields = getAllFields(objectClass, null); - - // Iterate through all the fields in the object - fieldIteration: - for (int ii = 0; ii < fields.length; ii++) { - - // make private fields accessible so we can access their values. - // This is discouraged as it can introduce security vulnerabilities so care - // should be taken in this section of the code to not do anything other than - // read from this field so it can be saved in the audit log - fields[ii].setAccessible(true); - - // if the current field is static, transient or final then don't log it as - // these modifiers are v.unlikely to be part of the data model. - if (Modifier.isTransient(fields[ii].getModifiers()) - || Modifier.isFinal(fields[ii].getModifiers()) - || Modifier.isStatic(fields[ii].getModifiers())) { - continue fieldIteration; - } - - String fieldName = fields[ii].getName(); - if ((!fieldName.equals("id")) - // bugzilla 2574 - // && (!fieldName.equals("lastupdated")) - && (!fieldName.equals("sysUserId")) - && (!fieldName.equals("systemUser")) - && (!fieldName.equals("originalLastupdated"))) { - // bugzilla 2578 - // && (!fieldName.equals("collectionDateForDisplay")) - // && (!fieldName.equals("collectionTimeForDisplay")) ) { - Class interfaces[] = fields[ii].getType().getInterfaces(); - for (int i = 0; i < interfaces.length; ) { - if (interfaces[i].equals(java.util.Collection.class)) { - continue fieldIteration; - } - i++; + if (newFields != null) { + newFieldsSize = newFields.length; } - String propertyNewState; - String propertyPreUpdateState; + Field[] totalFields = new Field[fieldsSize + newFieldsSize]; - // get new field values - try { - if (newObject != null) { - Object objPropNewState = fields[ii].get(newObject); - if (objPropNewState != null) { - propertyNewState = objPropNewState.toString(); - } else { - propertyNewState = ""; - } - } else { - propertyNewState = ""; - } - } catch (IllegalAccessException e) { - // buzilla 2154 - LogEvent.logError(e); - propertyNewState = ""; + if (fieldsSize > 0) { + System.arraycopy(fields, 0, totalFields, 0, fieldsSize); } - try { - Object objPreUpdateState = fields[ii].get(existingObject); - if (objPreUpdateState != null) { - propertyPreUpdateState = objPreUpdateState.toString(); - } else { - propertyPreUpdateState = ""; - } - } catch (IllegalArgumentException e) { - propertyPreUpdateState = ""; - } catch (IllegalAccessException e) { - // buzilla 2154 - LogEvent.logError(e); - propertyPreUpdateState = ""; + if (newFieldsSize > 0) { + System.arraycopy(newFields, 0, totalFields, fieldsSize, newFieldsSize); } - // bugzilla 2134 fixed the analysis_qaevent completed date problem - // bugzilla 2122 fixed the sample collection date problem - if (fieldName.equals("qaEvent") || fieldName.equals("sample")) { - LabelValuePair lvb = - processLabelValueFixes(fieldName, propertyPreUpdateState, existingObject, newObject); - if (lvb != null) { - String label = lvb.getLabel(); - String value = lvb.getValue(); - optionList.add(new LabelValuePair(label, value)); - } + Class superClass = objectClass.getSuperclass(); + + Field[] finalFieldsArray; + + if (superClass != null && !superClass.equals(Object.class)) { + finalFieldsArray = getAllFields(superClass, totalFields); } else { - // Ignore the parent class if any, only compare the current level - if (propertyNewState.startsWith("{org.openelisglobal")) { - propertyNewState = propertyPreUpdateState; - } - if (propertyPreUpdateState.startsWith("{org.openelisglobal")) { - propertyPreUpdateState = propertyNewState; - } - - // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","TABLE NAME: " + - // tableName); - // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","FIELD NAME: " + - // fieldName); - // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","PRE UPDATE: " + - // propertyPreUpdateState); - // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","NEW UPDATE: " + - // propertyNewState); - // LogEvent.logInfo("","","\n"); - - // Now we have the two property values - compare them - if (propertyNewState.equals(propertyPreUpdateState)) { - continue; // Values haven't changed so loop to next property - } else { - LabelValuePair lvb = - processLabelValue(fieldName, propertyPreUpdateState, existingObject, newObject); - if (lvb != null) { - optionList.add(new LabelValuePair(lvb.getLabel(), lvb.getValue())); - } - } + finalFieldsArray = totalFields; } - } - } - String xml = null; - if (optionList.size() > 0) { - xml = getXMLFormat(optionList); + return finalFieldsArray; } - return xml; - } - - /** - * Process and compare the child value objects using java reflection - * - * @param fieldName the method name - * @param propertyPreUpdateState the previous value - * @param existingObject the old data object - * @param newObject the new data object - * @return a label value object bugzilla 2134 fixed the analysis_qaevent completed date problem - * bugzilla 2122 fixed the sample collection_date problem - */ - private LabelValuePair processLabelValueFixes( - String fieldName, String propertyPreUpdateState, Object existingObject, Object newObject) { - LabelValuePair lvb = null; - Method m1; - Method m2; - Object o1 = null; - Object o2 = null; - - try { - if (fieldName.equals("qaEvent")) { - fieldName = "completedDate"; - m1 = existingObject.getClass().getMethod("getCompletedDate", new Class[0]); - o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - m2 = newObject.getClass().getMethod("getCompletedDate", new Class[0]); - o2 = m2.invoke(newObject, (Object[]) new Class[0]); - } - if (fieldName.equals("sample")) { - fieldName = "collectionDate"; - try { - m1 = existingObject.getClass().getMethod("getCollectionDate", new Class[0]); - o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - m2 = newObject.getClass().getMethod("getCollectionDate", new Class[0]); - o2 = m2.invoke(newObject, (Object[]) new Class[0]); - } catch (NoSuchMethodException e) { - LogEvent.logWarn( - this.getClass().getSimpleName(), - "processLabelValueFixes", - "ignoring NoSuchMethodException getCollectionDate() for object of type: " - + existingObject.getClass().getName()); - // ignore for SampleItem (which does not have getCollectionDate method + /** + * Logs changes to persistent data + * + * @param newObject the object being saved, updated or deleted + * @param existingObject the existing object in the database. Used only for + * updates + * @param tableName the name of the table being logged. + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws InvocationTargetException + */ + private String getChanges(BaseObject newObject, BaseObject existingObject, String tableName) { + + // bugzilla 1857 + Vector optionList = new Vector<>(); + Class objectClass = existingObject.getClass(); + // get an array of all fields in the class including those in superclasses if + // this is a subclass. + Field[] fields = getAllFields(objectClass, null); + + // Iterate through all the fields in the object + fieldIteration: for (int ii = 0; ii < fields.length; ii++) { + + // make private fields accessible so we can access their values. + // This is discouraged as it can introduce security vulnerabilities so care + // should be taken in this section of the code to not do anything other than + // read from this field so it can be saved in the audit log + fields[ii].setAccessible(true); + + // if the current field is static, transient or final then don't log it as + // these modifiers are v.unlikely to be part of the data model. + if (Modifier.isTransient(fields[ii].getModifiers()) || Modifier.isFinal(fields[ii].getModifiers()) + || Modifier.isStatic(fields[ii].getModifiers())) { + continue fieldIteration; + } + + String fieldName = fields[ii].getName(); + if ((!fieldName.equals("id")) + // bugzilla 2574 + // && (!fieldName.equals("lastupdated")) + && (!fieldName.equals("sysUserId")) && (!fieldName.equals("systemUser")) + && (!fieldName.equals("originalLastupdated"))) { + // bugzilla 2578 + // && (!fieldName.equals("collectionDateForDisplay")) + // && (!fieldName.equals("collectionTimeForDisplay")) ) { + Class interfaces[] = fields[ii].getType().getInterfaces(); + for (int i = 0; i < interfaces.length;) { + if (interfaces[i].equals(java.util.Collection.class)) { + continue fieldIteration; + } + i++; + } + + String propertyNewState; + String propertyPreUpdateState; + + // get new field values + try { + if (newObject != null) { + Object objPropNewState = fields[ii].get(newObject); + if (objPropNewState != null) { + propertyNewState = objPropNewState.toString(); + } else { + propertyNewState = ""; + } + } else { + propertyNewState = ""; + } + } catch (IllegalAccessException e) { + // buzilla 2154 + LogEvent.logError(e); + propertyNewState = ""; + } + + try { + Object objPreUpdateState = fields[ii].get(existingObject); + if (objPreUpdateState != null) { + propertyPreUpdateState = objPreUpdateState.toString(); + } else { + propertyPreUpdateState = ""; + } + } catch (IllegalArgumentException e) { + propertyPreUpdateState = ""; + } catch (IllegalAccessException e) { + // buzilla 2154 + LogEvent.logError(e); + propertyPreUpdateState = ""; + } + + // bugzilla 2134 fixed the analysis_qaevent completed date problem + // bugzilla 2122 fixed the sample collection date problem + if (fieldName.equals("qaEvent") || fieldName.equals("sample")) { + LabelValuePair lvb = processLabelValueFixes(fieldName, propertyPreUpdateState, existingObject, + newObject); + if (lvb != null) { + String label = lvb.getLabel(); + String value = lvb.getValue(); + optionList.add(new LabelValuePair(label, value)); + } + } else { + // Ignore the parent class if any, only compare the current level + if (propertyNewState.startsWith("{org.openelisglobal")) { + propertyNewState = propertyPreUpdateState; + } + if (propertyPreUpdateState.startsWith("{org.openelisglobal")) { + propertyPreUpdateState = propertyNewState; + } + + // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","TABLE NAME: " + + // tableName); + // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","FIELD NAME: " + + // fieldName); + // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","PRE UPDATE: " + + // propertyPreUpdateState); + // LogEvent.logInfo("AuditTrailDAOImpl","getChanges","NEW UPDATE: " + + // propertyNewState); + // LogEvent.logInfo("","","\n"); + + // Now we have the two property values - compare them + if (propertyNewState.equals(propertyPreUpdateState)) { + continue; // Values haven't changed so loop to next property + } else { + LabelValuePair lvb = processLabelValue(fieldName, propertyPreUpdateState, existingObject, + newObject); + if (lvb != null) { + optionList.add(new LabelValuePair(lvb.getLabel(), lvb.getValue())); + } + } + } + } } - } - - String oldID = ""; - String newID = ""; - if (o1 != null) { - oldID = o1.toString(); - } - - if (o2 != null) { - newID = o2.toString(); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = newID; - } - - } catch (NoSuchMethodException - | IllegalAccessException - | IllegalArgumentException - | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValueFixes()", e); - } - if (((fieldName != null) && (fieldName.length() > 0)) - && ((propertyPreUpdateState != null) && (propertyPreUpdateState.length() > 0))) { - if (propertyPreUpdateState.equals("{null}") || propertyPreUpdateState.equals("null")) { - lvb = new LabelValuePair(); - lvb.setLabel(fieldName); - lvb.setValue(""); - } else { - lvb = new LabelValuePair(); - lvb.setLabel(fieldName); - lvb.setValue(propertyPreUpdateState); - } + String xml = null; + if (optionList.size() > 0) { + xml = getXMLFormat(optionList); + } + + return xml; } - return lvb; - } - - /** - * Process and compare the child value objects using java reflection - * - * @param fieldName the method name - * @param propertyPreUpdateState the previous value - * @param existingObject the old data object - * @param newObject the new data object - * @return a label value object - */ - private LabelValuePair processLabelValue( - String fieldName, String propertyPreUpdateState, Object existingObject, Object newObject) { - - LabelValuePair lvb = null; - if (propertyPreUpdateState.startsWith("{org.openelisglobal")) { - if (fieldName.equals("test")) { - try { - Method m1 = existingObject.getClass().getMethod("getTest", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getTest", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("testSection")) { - try { - Method m1 = existingObject.getClass().getMethod("getTestSection", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getTestSection", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException - | IllegalAccessException - | IllegalArgumentException - | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("county")) { - try { - Method m1 = existingObject.getClass().getMethod("getCounty", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getCounty", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (RuntimeException - | NoSuchMethodException - | IllegalAccessException - | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("region")) { - try { - Method m1 = existingObject.getClass().getMethod("getRegion", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getRegion", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException - | InvocationTargetException - | NoSuchMethodException - | SecurityException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("scriptlet")) { - try { - Method m1 = existingObject.getClass().getMethod("getScriptlet", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getScriptlet", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (RuntimeException - | NoSuchMethodException - | IllegalAccessException - | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("organization")) { - try { - Method m1 = existingObject.getClass().getMethod("getOrganization", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getOrganization", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("panel")) { - try { - Method m1 = existingObject.getClass().getMethod("getPanel", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getPanel", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("person")) { - try { - Method m1 = existingObject.getClass().getMethod("getPerson", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getPerson", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("testResult")) { - try { - Method m1 = existingObject.getClass().getMethod("getTestResult", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getTestResult", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("analysis")) { - try { - Method m1 = existingObject.getClass().getMethod("getAnalysis", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getAnalysis", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (RuntimeException - | NoSuchMethodException - | IllegalAccessException - | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("analyte")) { - try { - Method m1 = existingObject.getClass().getMethod("getAnalyte", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getAnalyte", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("sampleItem")) { - try { - Method m1 = existingObject.getClass().getMethod("getSampleItem", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getSampleItem", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("parentAnalysis")) { - try { - Method m1 = existingObject.getClass().getMethod("getParentAnalysis", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getParentAnalysis", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("parentResult")) { - try { - Method m1 = existingObject.getClass().getMethod("getParentResult", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getParentResult", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("sample")) { - try { - Method m1 = existingObject.getClass().getMethod("getSample", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getSample", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("method")) { - try { - Method m1 = existingObject.getClass().getMethod("getMethod", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getMethod", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("testTrailer")) { - try { - Method m1 = existingObject.getClass().getMethod("getTestTrailer", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getTestTrailer", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("unitOfMeasure")) { - try { - Method m1 = existingObject.getClass().getMethod("getUnitOfMeasure", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getUnitOfMeasure", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("testAnalyte")) { - try { - Method m1 = existingObject.getClass().getMethod("getTestAnalyte", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getTestAnalyte", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); - } - } else if (fieldName.equals("label")) { + /** + * Process and compare the child value objects using java reflection + * + * @param fieldName the method name + * @param propertyPreUpdateState the previous value + * @param existingObject the old data object + * @param newObject the new data object + * @return a label value object bugzilla 2134 fixed the analysis_qaevent + * completed date problem bugzilla 2122 fixed the sample collection_date + * problem + */ + private LabelValuePair processLabelValueFixes(String fieldName, String propertyPreUpdateState, + Object existingObject, Object newObject) { + LabelValuePair lvb = null; + Method m1; + Method m2; + Object o1 = null; + Object o2 = null; + try { - Method m1 = existingObject.getClass().getMethod("getLabel", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getLabel", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + if (fieldName.equals("qaEvent")) { + fieldName = "completedDate"; + m1 = existingObject.getClass().getMethod("getCompletedDate", new Class[0]); + o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + m2 = newObject.getClass().getMethod("getCompletedDate", new Class[0]); + o2 = m2.invoke(newObject, (Object[]) new Class[0]); + } + if (fieldName.equals("sample")) { + fieldName = "collectionDate"; + try { + m1 = existingObject.getClass().getMethod("getCollectionDate", new Class[0]); + o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + m2 = newObject.getClass().getMethod("getCollectionDate", new Class[0]); + o2 = m2.invoke(newObject, (Object[]) new Class[0]); + } catch (NoSuchMethodException e) { + LogEvent.logWarn(this.getClass().getSimpleName(), "processLabelValueFixes", + "ignoring NoSuchMethodException getCollectionDate() for object of type: " + + existingObject.getClass().getName()); + // ignore for SampleItem (which does not have getCollectionDate method + } + } + + String oldID = ""; + String newID = ""; + if (o1 != null) { + oldID = o1.toString(); + } + + if (o2 != null) { + newID = o2.toString(); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = newID; + } + + } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValueFixes()", e); } - } else if (fieldName.equals("city")) { - try { - Method m1 = existingObject.getClass().getMethod("getCity", new Class[0]); - Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); - - Method m2 = newObject.getClass().getMethod("getCity", new Class[0]); - Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); - - String oldID = ""; - String newID = ""; - if (o1 != null) { - Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); - oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); - } - - if (o2 != null) { - Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); - newID = (String) m22.invoke(o2, (Object[]) new Class[0]); - } - - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } - - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + + if (((fieldName != null) && (fieldName.length() > 0)) + && ((propertyPreUpdateState != null) && (propertyPreUpdateState.length() > 0))) { + if (propertyPreUpdateState.equals("{null}") || propertyPreUpdateState.equals("null")) { + lvb = new LabelValuePair(); + lvb.setLabel(fieldName); + lvb.setValue(""); + } else { + lvb = new LabelValuePair(); + lvb.setLabel(fieldName); + lvb.setValue(propertyPreUpdateState); + } } - } else if (fieldName.equals("addedTest")) { - // testreflex - try { - org.openelisglobal.testreflex.valueholder.TestReflex data = - (org.openelisglobal.testreflex.valueholder.TestReflex) existingObject; - org.openelisglobal.testreflex.valueholder.TestReflex data2 = - (org.openelisglobal.testreflex.valueholder.TestReflex) newObject; + return lvb; + } - String oldID = ""; - String newID = ""; - if ((data.getAddedTest().getId() != null)) { - oldID = data.getAddedTest().getId(); - } + /** + * Process and compare the child value objects using java reflection + * + * @param fieldName the method name + * @param propertyPreUpdateState the previous value + * @param existingObject the old data object + * @param newObject the new data object + * @return a label value object + */ + private LabelValuePair processLabelValue(String fieldName, String propertyPreUpdateState, Object existingObject, + Object newObject) { + + LabelValuePair lvb = null; + if (propertyPreUpdateState.startsWith("{org.openelisglobal")) { + if (fieldName.equals("test")) { + try { + Method m1 = existingObject.getClass().getMethod("getTest", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getTest", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("testSection")) { + try { + Method m1 = existingObject.getClass().getMethod("getTestSection", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getTestSection", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("county")) { + try { + Method m1 = existingObject.getClass().getMethod("getCounty", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getCounty", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (RuntimeException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("region")) { + try { + Method m1 = existingObject.getClass().getMethod("getRegion", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getRegion", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException + | SecurityException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("scriptlet")) { + try { + Method m1 = existingObject.getClass().getMethod("getScriptlet", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getScriptlet", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (RuntimeException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("organization")) { + try { + Method m1 = existingObject.getClass().getMethod("getOrganization", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getOrganization", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("panel")) { + try { + Method m1 = existingObject.getClass().getMethod("getPanel", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getPanel", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("person")) { + try { + Method m1 = existingObject.getClass().getMethod("getPerson", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getPerson", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("testResult")) { + try { + Method m1 = existingObject.getClass().getMethod("getTestResult", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getTestResult", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("analysis")) { + try { + Method m1 = existingObject.getClass().getMethod("getAnalysis", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getAnalysis", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (RuntimeException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("analyte")) { + try { + Method m1 = existingObject.getClass().getMethod("getAnalyte", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getAnalyte", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("sampleItem")) { + try { + Method m1 = existingObject.getClass().getMethod("getSampleItem", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getSampleItem", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("parentAnalysis")) { + try { + Method m1 = existingObject.getClass().getMethod("getParentAnalysis", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getParentAnalysis", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("parentResult")) { + try { + Method m1 = existingObject.getClass().getMethod("getParentResult", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getParentResult", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("sample")) { + try { + Method m1 = existingObject.getClass().getMethod("getSample", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getSample", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("method")) { + try { + Method m1 = existingObject.getClass().getMethod("getMethod", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getMethod", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("testTrailer")) { + try { + Method m1 = existingObject.getClass().getMethod("getTestTrailer", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getTestTrailer", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("unitOfMeasure")) { + try { + Method m1 = existingObject.getClass().getMethod("getUnitOfMeasure", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getUnitOfMeasure", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("testAnalyte")) { + try { + Method m1 = existingObject.getClass().getMethod("getTestAnalyte", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getTestAnalyte", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("label")) { + try { + Method m1 = existingObject.getClass().getMethod("getLabel", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getLabel", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("city")) { + try { + Method m1 = existingObject.getClass().getMethod("getCity", new Class[0]); + Object o1 = m1.invoke(existingObject, (Object[]) new Class[0]); + + Method m2 = newObject.getClass().getMethod("getCity", new Class[0]); + Object o2 = m2.invoke(newObject, (Object[]) new Class[0]); + + String oldID = ""; + String newID = ""; + if (o1 != null) { + Method m11 = o1.getClass().getMethod("getStringId", new Class[0]); + oldID = (String) m11.invoke(o1, (Object[]) new Class[0]); + } + + if (o2 != null) { + Method m22 = o2.getClass().getMethod("getStringId", new Class[0]); + newID = (String) m22.invoke(o2, (Object[]) new Class[0]); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } else if (fieldName.equals("addedTest")) { + // testreflex + try { + org.openelisglobal.testreflex.valueholder.TestReflex data = (org.openelisglobal.testreflex.valueholder.TestReflex) existingObject; + + org.openelisglobal.testreflex.valueholder.TestReflex data2 = (org.openelisglobal.testreflex.valueholder.TestReflex) newObject; + + String oldID = ""; + String newID = ""; + if ((data.getAddedTest().getId() != null)) { + oldID = data.getAddedTest().getId(); + } + + if ((data2.getAddedTest().getId() != null)) { + newID = data2.getAddedTest().getId(); + } + + if (oldID.compareTo(newID) == 0) { + fieldName = null; + propertyPreUpdateState = null; + } else { + propertyPreUpdateState = oldID; + } + + } catch (RuntimeException e) { + // buzilla 2154 + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + } + } + } - if ((data2.getAddedTest().getId() != null)) { - newID = data2.getAddedTest().getId(); - } + if (((fieldName != null) && (fieldName.length() > 0)) && + // bugzilla 2578 (blank to filled in collection date does not appear in history + ((propertyPreUpdateState != null))) { + if (propertyPreUpdateState.equals("{null}") || propertyPreUpdateState.equals("null")) { + lvb = new LabelValuePair(); + lvb.setLabel(fieldName); + lvb.setValue(""); + } else { + lvb = new LabelValuePair(); + lvb.setLabel(fieldName); + lvb.setValue(propertyPreUpdateState); + } + } - if (oldID.compareTo(newID) == 0) { - fieldName = null; - propertyPreUpdateState = null; - } else { - propertyPreUpdateState = oldID; - } + return lvb; + } - } catch (RuntimeException e) { - // buzilla 2154 - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail processLabelValue()", e); + /** + * Convert to xml format + * + * @param list the list to be converted + * @return xml string + */ + private String getXMLFormat(Vector list) { + StringBuilder xml = new StringBuilder(); + + for (int i = 0; i < list.size(); i++) { + LabelValuePair lvp = (LabelValuePair) list.elementAt(i); + XMLUtil.appendKeyValue(lvp.getLabel(), lvp.getValue(), xml); + xml.append("\n"); } - } + + return xml.toString(); } - if (((fieldName != null) && (fieldName.length() > 0)) - && - // bugzilla 2578 (blank to filled in collection date does not appear in history - ((propertyPreUpdateState != null))) { - if (propertyPreUpdateState.equals("{null}") || propertyPreUpdateState.equals("null")) { - lvb = new LabelValuePair(); - lvb.setLabel(fieldName); - lvb.setValue(""); - } else { - lvb = new LabelValuePair(); - lvb.setLabel(fieldName); - lvb.setValue(propertyPreUpdateState); - } + /** + * Convert to xml format by reading the table bases on it's id (dom4j) + * + * @param table the table name + * @param id the primary id + * @return xml string + */ + @Override + @Transactional(readOnly = true) + public String getXML(String table, String id) throws LIMSRuntimeException { + // org.hibernate.Session session = sessionFactory.getCurrentSession(); + // org.hibernate.Session dom4jSession = + // session.getSession(org.hibernate.EntityMode.DOM4J); + // + // Element elem = (Element) dom4jSession.createQuery("from " + table + " where + // id=" + id).uniqueResult(); + // java.io.StringWriter sw = new java.io.StringWriter(); + // if (elem != null) { + // try { + // Document doc = DocumentHelper.createDocument(); + // doc.add(elem); + // OutputFormat format = OutputFormat.createPrettyPrint(); + // XMLWriter writer = new XMLWriter(sw, format); + // writer.write(doc); + // writer.flush(); + // writer.close(); + // + // return sw.toString(); + // } catch (RuntimeException e) { + // // buzilla 2154 + // LogEvent.logError("AuditTrailDAOImpl", "getXML()", e.toString()); + // throw new LIMSRuntimeException("Error in AuditTrail getXML()", e); + // } + // } + return null; } - return lvb; - } - - /** - * Convert to xml format - * - * @param list the list to be converted - * @return xml string - */ - private String getXMLFormat(Vector list) { - StringBuilder xml = new StringBuilder(); - - for (int i = 0; i < list.size(); i++) { - LabelValuePair lvp = (LabelValuePair) list.elementAt(i); - XMLUtil.appendKeyValue(lvp.getLabel(), lvp.getValue(), xml); - xml.append("\n"); + /** + * Convert to xml format by reading the table bases on it's id ( oracle dbms ) + * + * @param table the table name + * @param id the primary id + * @return xml string + */ + @Override + @Transactional(readOnly = true) + public String getXMLData(String table, String id) throws LIMSRuntimeException { + // StringBuffer xml; + // + // LogEvent.logDebug("AuditTrailDAOImpl", "getXMLData()", "getting History + // instance"); + // try { + // String out = (String) HibernateUtil + // .getSession().createSQLQuery("select to_char(dbms_xmlgen.getxml('select * + // from " + table + // + " where id=" + id + "')) as xml from dual") + // .addScalar("xml", Hibernate.STRING).uniqueResult(); + // xml = new StringBuffer().append(out); + // + // return xml.toString(); + // + // } catch (RuntimeException e) { + // LogEvent.logError("AuditTrailDAOImpl", "getXMLData()", e.toString()); + // throw new LIMSRuntimeException("Error in AuditTrail getXMLData()", e); + // } + return null; } - return xml.toString(); - } - - /** - * Convert to xml format by reading the table bases on it's id (dom4j) - * - * @param table the table name - * @param id the primary id - * @return xml string - */ - @Override - @Transactional(readOnly = true) - public String getXML(String table, String id) throws LIMSRuntimeException { - // org.hibernate.Session session = sessionFactory.getCurrentSession(); - // org.hibernate.Session dom4jSession = - // session.getSession(org.hibernate.EntityMode.DOM4J); - // - // Element elem = (Element) dom4jSession.createQuery("from " + table + " where - // id=" + id).uniqueResult(); - // java.io.StringWriter sw = new java.io.StringWriter(); - // if (elem != null) { - // try { - // Document doc = DocumentHelper.createDocument(); - // doc.add(elem); - // OutputFormat format = OutputFormat.createPrettyPrint(); - // XMLWriter writer = new XMLWriter(sw, format); - // writer.write(doc); - // writer.flush(); - // writer.close(); - // - // return sw.toString(); - // } catch (RuntimeException e) { - // // buzilla 2154 - // LogEvent.logError("AuditTrailDAOImpl", "getXML()", e.toString()); - // throw new LIMSRuntimeException("Error in AuditTrail getXML()", e); - // } - // } - return null; - } - - /** - * Convert to xml format by reading the table bases on it's id ( oracle dbms ) - * - * @param table the table name - * @param id the primary id - * @return xml string - */ - @Override - @Transactional(readOnly = true) - public String getXMLData(String table, String id) throws LIMSRuntimeException { - // StringBuffer xml; - // - // LogEvent.logDebug("AuditTrailDAOImpl", "getXMLData()", "getting History - // instance"); - // try { - // String out = (String) HibernateUtil - // .getSession().createSQLQuery("select to_char(dbms_xmlgen.getxml('select * - // from " + table - // + " where id=" + id + "')) as xml from dual") - // .addScalar("xml", Hibernate.STRING).uniqueResult(); - // xml = new StringBuffer().append(out); - // - // return xml.toString(); - // - // } catch (RuntimeException e) { - // LogEvent.logError("AuditTrailDAOImpl", "getXMLData()", e.toString()); - // throw new LIMSRuntimeException("Error in AuditTrail getXMLData()", e); - // } - return null; - } - - /** - * Save the object into history table - * - * @param history the history object being saved - */ - private void insertData(History history) throws LIMSRuntimeException { - historyService.insert(history); - } + /** + * Save the object into history table + * + * @param history the history object being saved + */ + private void insertData(History history) throws LIMSRuntimeException { + historyService.insert(history); + } } diff --git a/src/main/java/org/openelisglobal/audittrail/daoimpl/HistoryDAOImpl.java b/src/main/java/org/openelisglobal/audittrail/daoimpl/HistoryDAOImpl.java index a45b6cce55..df2785cc21 100644 --- a/src/main/java/org/openelisglobal/audittrail/daoimpl/HistoryDAOImpl.java +++ b/src/main/java/org/openelisglobal/audittrail/daoimpl/HistoryDAOImpl.java @@ -15,38 +15,36 @@ @Component @Transactional public class HistoryDAOImpl extends BaseDAOImpl implements HistoryDAO { - HistoryDAOImpl() { - super(History.class); - } + HistoryDAOImpl() { + super(History.class); + } - @Override - public List getHistoryByRefIdAndRefTableId(String refId, String tableId) - throws LIMSRuntimeException { - History history = new History(); - history.setReferenceId(refId); - history.setReferenceTable(tableId); - return getHistoryByRefIdAndRefTableId(history); - } + @Override + public List getHistoryByRefIdAndRefTableId(String refId, String tableId) throws LIMSRuntimeException { + History history = new History(); + history.setReferenceId(refId); + history.setReferenceTable(tableId); + return getHistoryByRefIdAndRefTableId(history); + } - @Override - @Transactional(readOnly = true) - public List getHistoryByRefIdAndRefTableId(History history) throws LIMSRuntimeException { - String refId = history.getReferenceId(); - String tableId = history.getReferenceTable(); - List list; + @Override + @Transactional(readOnly = true) + public List getHistoryByRefIdAndRefTableId(History history) throws LIMSRuntimeException { + String refId = history.getReferenceId(); + String tableId = history.getReferenceTable(); + List list; - try { - String sql = - "from History h where h.referenceId = :refId and h.referenceTable = :tableId order by" - + " h.timestamp desc, h.activity desc"; - Query query = entityManager.unwrap(Session.class).createQuery(sql, History.class); - query.setParameter("refId", Integer.parseInt(refId)); - query.setParameter("tableId", Integer.parseInt(tableId)); - list = query.list(); - } catch (HibernateException e) { - LogEvent.logError(e); - throw new LIMSRuntimeException("Error in AuditTrail getHistoryByRefIdAndRefTableId()", e); + try { + String sql = "from History h where h.referenceId = :refId and h.referenceTable = :tableId order by" + + " h.timestamp desc, h.activity desc"; + Query query = entityManager.unwrap(Session.class).createQuery(sql, History.class); + query.setParameter("refId", Integer.parseInt(refId)); + query.setParameter("tableId", Integer.parseInt(tableId)); + list = query.list(); + } catch (HibernateException e) { + LogEvent.logError(e); + throw new LIMSRuntimeException("Error in AuditTrail getHistoryByRefIdAndRefTableId()", e); + } + return list; } - return list; - } } diff --git a/src/main/java/org/openelisglobal/audittrail/form/AuditTrailViewForm.java b/src/main/java/org/openelisglobal/audittrail/form/AuditTrailViewForm.java index cadad3716b..189b06cd59 100644 --- a/src/main/java/org/openelisglobal/audittrail/form/AuditTrailViewForm.java +++ b/src/main/java/org/openelisglobal/audittrail/form/AuditTrailViewForm.java @@ -11,59 +11,62 @@ // used for viewing only, does not need validation public class AuditTrailViewForm extends BaseForm { - @SafeHtml(level = SafeHtml.SafeListLevel.NONE) - private String accessionNumberSearch = ""; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE) + private String accessionNumberSearch = ""; - @Valid private List log; + @Valid + private List log; - @SafeHtml(level = SafeHtml.SafeListLevel.NONE) - private String accessionNumber = ""; + @SafeHtml(level = SafeHtml.SafeListLevel.NONE) + private String accessionNumber = ""; - @Valid private SampleOrderItem sampleOrderItems; + @Valid + private SampleOrderItem sampleOrderItems; - @Valid private PatientManagementInfo patientProperties; + @Valid + private PatientManagementInfo patientProperties; - public AuditTrailViewForm() { - setFormName("AuditTrailViewForm"); - } + public AuditTrailViewForm() { + setFormName("AuditTrailViewForm"); + } - public String getAccessionNumberSearch() { - return accessionNumberSearch; - } + public String getAccessionNumberSearch() { + return accessionNumberSearch; + } - public void setAccessionNumberSearch(String accessionNumberSearch) { - this.accessionNumberSearch = accessionNumberSearch; - } + public void setAccessionNumberSearch(String accessionNumberSearch) { + this.accessionNumberSearch = accessionNumberSearch; + } - public List getLog() { - return log; - } + public List getLog() { + return log; + } - public void setLog(List log) { - this.log = log; - } + public void setLog(List log) { + this.log = log; + } - public String getAccessionNumber() { - return accessionNumber; - } + public String getAccessionNumber() { + return accessionNumber; + } - public void setAccessionNumber(String accessionNumber) { - this.accessionNumber = accessionNumber; - } + public void setAccessionNumber(String accessionNumber) { + this.accessionNumber = accessionNumber; + } - public SampleOrderItem getSampleOrderItems() { - return sampleOrderItems; - } + public SampleOrderItem getSampleOrderItems() { + return sampleOrderItems; + } - public void setSampleOrderItems(SampleOrderItem sampleOrderItems) { - this.sampleOrderItems = sampleOrderItems; - } + public void setSampleOrderItems(SampleOrderItem sampleOrderItems) { + this.sampleOrderItems = sampleOrderItems; + } - public PatientManagementInfo getPatientProperties() { - return patientProperties; - } + public PatientManagementInfo getPatientProperties() { + return patientProperties; + } - public void setPatientProperties(PatientManagementInfo patientProperties) { - this.patientProperties = patientProperties; - } + public void setPatientProperties(PatientManagementInfo patientProperties) { + this.patientProperties = patientProperties; + } } diff --git a/src/main/java/org/openelisglobal/audittrail/valueholder/History.java b/src/main/java/org/openelisglobal/audittrail/valueholder/History.java index e4d55ae2c3..795348fcf8 100644 --- a/src/main/java/org/openelisglobal/audittrail/valueholder/History.java +++ b/src/main/java/org/openelisglobal/audittrail/valueholder/History.java @@ -22,71 +22,71 @@ */ public class History extends BaseObject { - private String id; - private String referenceId; - private String referenceTable; - private Timestamp timestamp; - private String activity; - private byte[] changes; - private String sys_user_id; - - @Override - public String getSysUserId() { - return sys_user_id; - } - - @Override - public void setSysUserId(String sys_user_id) { - this.sys_user_id = sys_user_id; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - public String getReferenceId() { - return referenceId; - } - - public void setReferenceId(String referenceId) { - this.referenceId = referenceId; - } - - public String getReferenceTable() { - return referenceTable; - } - - public void setReferenceTable(String referenceTable) { - this.referenceTable = referenceTable; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - - public String getActivity() { - return activity; - } - - public void setActivity(String activity) { - this.activity = activity; - } - - public byte[] getChanges() { - return changes; - } - - public void setChanges(byte[] changes) { - this.changes = changes; - } + private String id; + private String referenceId; + private String referenceTable; + private Timestamp timestamp; + private String activity; + private byte[] changes; + private String sys_user_id; + + @Override + public String getSysUserId() { + return sys_user_id; + } + + @Override + public void setSysUserId(String sys_user_id) { + this.sys_user_id = sys_user_id; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + public String getReferenceId() { + return referenceId; + } + + public void setReferenceId(String referenceId) { + this.referenceId = referenceId; + } + + public String getReferenceTable() { + return referenceTable; + } + + public void setReferenceTable(String referenceTable) { + this.referenceTable = referenceTable; + } + + public Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(Timestamp timestamp) { + this.timestamp = timestamp; + } + + public String getActivity() { + return activity; + } + + public void setActivity(String activity) { + this.activity = activity; + } + + public byte[] getChanges() { + return changes; + } + + public void setChanges(byte[] changes) { + this.changes = changes; + } } diff --git a/src/main/java/org/openelisglobal/barcode/BarcodeLabelMaker.java b/src/main/java/org/openelisglobal/barcode/BarcodeLabelMaker.java index f390b30daa..048facd24e 100644 --- a/src/main/java/org/openelisglobal/barcode/BarcodeLabelMaker.java +++ b/src/main/java/org/openelisglobal/barcode/BarcodeLabelMaker.java @@ -47,500 +47,482 @@ import org.openelisglobal.test.valueholder.Test; /** - * Class for taking lists of Label objects and turning them into a printable format + * Class for taking lists of Label objects and turning them into a printable + * format * * @author Caleb */ public class BarcodeLabelMaker { - // number of columns for label layout grid - private static int NUM_COLUMNS = 20; + // number of columns for label layout grid + private static int NUM_COLUMNS = 20; - // stores labels between generation and creating pdf - private ArrayList