List of usage examples for org.hibernate Query getQueryString
String getQueryString();
From source file:de.fhdo.terminologie.ws.search.ListCodeSystemConcepts.java
License:Apache License
public ListCodeSystemConceptsResponseType ListCodeSystemConcepts(ListCodeSystemConceptsRequestType parameter, org.hibernate.Session session, boolean noLimit, String ipAddress) { if (logger.isInfoEnabled()) logger.info("====== ListCodeSystemConcepts gestartet ======"); boolean createHibernateSession = (session == null); // Return-Informationen anlegen ListCodeSystemConceptsResponseType response = new ListCodeSystemConceptsResponseType(); response.setReturnInfos(new ReturnType()); // Parameter prfen if (validateParameter(parameter, response) == false) { logger.debug("Parameter falsch"); return response; // Fehler bei den Parametern }/*from www . j av a2 s. c o m*/ // Login-Informationen auswerten (gilt fr jeden Webservice) boolean loggedIn = false; AuthenticateInfos loginInfoType = new AuthenticateInfos(); if (parameter != null && parameter.getLoginToken() != null) { loginInfoType = Authorization.authenticate(ipAddress, parameter.getLoginToken()); loggedIn = loginInfoType != null; } if (logger.isDebugEnabled()) { logger.debug("Benutzer ist eingeloggt: " + loggedIn); logger.debug("isLookForward: " + parameter.isLookForward()); } int maxPageSizeUserSpecific = 10; //int maxPageSizeUserSpecific = 1; if (parameter.getPagingParameter() != null && parameter.getPagingParameter().getUserPaging() != null) { if (parameter.getPagingParameter().getUserPaging()) maxPageSizeUserSpecific = Integer.valueOf(parameter.getPagingParameter().getPageSize()); } else { maxPageSizeUserSpecific = -1; } // PagingInfo int maxPageSize = 100; // Gibt an, wieviele Treffer maximal zurckgegeben werden //Warum loggedIn hier? Das ergibt am Termbrowser folgenden Bug: Wenn man eingeloggt ist kann man sich keine HugeFlat Concept Liste mehr ansehen e.g. LOINC! => WrongValueException! if (noLimit)// || loggedIn) { maxPageSize = -1; } else { String maxPageSizeStr = SysParameter.instance().getStringValue("maxPageSize", null, null); try { maxPageSize = Integer.parseInt(maxPageSizeStr); } catch (Exception e) { LoggingOutput.outputException(e, this); } } boolean traverseConceptsToRoot = false; int maxPageSizeSearch = 5; // Gibt an, wieviele Treffer bei einer Suche maximal zurckgegeben werden if (parameter != null && parameter.getSearchParameter() != null && parameter.getSearchParameter().getTraverseConceptsToRoot() != null && parameter.getSearchParameter().getTraverseConceptsToRoot()) { traverseConceptsToRoot = true; String maxPageSizeSearchStr = SysParameter.instance().getStringValue("maxPageSizeSearch", null, null); if (parameter != null && parameter.getSearchParameter() != null) { if (maxPageSizeSearchStr != null && maxPageSizeSearchStr.length() > 0) { try { maxPageSizeSearch = Integer.parseInt(maxPageSizeSearchStr); } catch (Exception e) { LoggingOutput.outputException(e, this); } } } } //maxPageSizeSearch = 2; //maxPageSize = 2; logger.debug("maxPageSize: " + maxPageSizeSearch); logger.debug("maxPageSizeSearch: " + maxPageSizeSearch); logger.debug("traverseConceptsToRoot: " + traverseConceptsToRoot); try { //List<CodeSystemConcept> conceptList = null; String codeSystemVersionOid = ""; long codeSystemVersionId = 0; if (parameter.getCodeSystem().getCodeSystemVersions() != null && parameter.getCodeSystem().getCodeSystemVersions().size() > 0) { CodeSystemVersion csv = (CodeSystemVersion) parameter.getCodeSystem().getCodeSystemVersions() .toArray()[0]; if (csv.getVersionId() != null) codeSystemVersionId = csv.getVersionId(); if (csv.getOid() != null) codeSystemVersionOid = csv.getOid(); } // Lizenzen prfen boolean validLicence = false; if (codeSystemVersionOid != null && codeSystemVersionOid.length() > 0) validLicence = LicenceHelper.getInstance().userHasLicence(loginInfoType.getUserId(), codeSystemVersionOid); else validLicence = LicenceHelper.getInstance().userHasLicence(loginInfoType.getUserId(), codeSystemVersionId); if (validLicence == false) { response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos().setMessage("Sie besitzen keine gltige Lizenz fr dieses Vokabular!"); return response; } else logger.debug("Lizenz fr Vokabular vorhanden!"); // Hibernate-Block, Session ffnen //org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession(); org.hibernate.Session hb_session = null; //org.hibernate.Transaction tx = null; if (createHibernateSession) { hb_session = HibernateUtil.getSessionFactory().openSession(); //hb_session.getTransaction().begin(); //tx = hb_session.beginTransaction(); } else { hb_session = session; //hb_session.getTransaction().begin(); } try // 2. try-catch-Block zum Abfangen von Hibernate-Fehlern { if (codeSystemVersionOid != null && codeSystemVersionOid.length() > 0) { logger.debug("get csv-id from oid"); // get csv-id from oid String hql = "from CodeSystemVersion csv" + " where csv.oid=:oid"; Query q = hb_session.createQuery(hql); q.setString("oid", codeSystemVersionOid); List<CodeSystemVersion> csvList = q.list(); if (csvList != null && csvList.size() > 0) { codeSystemVersionId = csvList.get(0).getVersionId(); logger.debug("found versionId from oid: " + codeSystemVersionId); } else { response.setCodeSystemEntity(new LinkedList<CodeSystemEntity>()); response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.WARN); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos().setMessage("Codesystem with given OID can't be found."); response.getReturnInfos().setCount(0); return response; } } if (codeSystemVersionId == 0 && parameter.getCodeSystem().getId() != null) { // Aktuelle Version des Vokabulars ermitteln long codeSystemId = parameter.getCodeSystem().getId(); CodeSystem cs = (CodeSystem) hb_session.get(CodeSystem.class, codeSystemId); if (cs != null) codeSystemVersionId = CodeSystemHelper.getCurrentVersionId(cs); } // HQL erstellen // Besonderheit hier: es drfen keine Werte nachgeladen werden // Beim Abruf eines ICD wre dieses sehr inperformant, da er fr // jeden Eintrag sonst nachladen wrde /* SELECT * FROM code_system_concept csc JOIN code_system_entity_version csev ON csc.codeSystemEntityVersionId=csev.versionId JOIN code_system_entity cse ON csev.versionId=cse.id JOIN code_system_version_entity_membership csvem ON cse.id=csvem.codeSystemEntityId LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc.codeSystemEntityVersionId WHERE csvem.codeSystemVersionId=10 */ String languageCd = ""; /*SELECT * FROM (SELECT csc.*, csev.*, csvem.isAxis, csvem.isMainClass, cse.* FROM code_system_concept csc JOIN code_system_entity_version csev ON csc.codeSystemEntityVersionId=csev.versionId JOIN code_system_entity cse ON csev.versionId=cse.id JOIN code_system_version_entity_membership csvem ON cse.id=csvem.codeSystemEntityId WHERE csvem.codeSystemVersionId=10 LIMIT 2) csc2 LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc2.codeSystemEntityVersionId*/ // //String sql = "SELECT * FROM (SELECT csc.*, csev.*, csvem.isAxis, csvem.isMainClass, cse.* FROM code_system_concept csc" String sql = "SELECT * FROM (SELECT csc.*, csev.*, csvem.isAxis, csvem.isMainClass, cse.*, csct.term translation_term, csct.termAbbrevation translation_termAbbrevation, csct.description translation_description, csct.languageCd translation_languageCd, csct.id translation_id " + " FROM code_system_concept csc" + " JOIN code_system_entity_version csev ON csc.codeSystemEntityVersionId=csev.versionId" + " JOIN code_system_entity cse ON csev.codeSystemEntityId=cse.id" + " JOIN code_system_version_entity_membership csvem ON cse.id=csvem.codeSystemEntityId" + " LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc.codeSystemEntityVersionId AND languageCd=:languageCd" //+ " LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc.codeSystemEntityVersionId AND_LANGUAGE_TERM" + " WHERE_TEIL) csc2" //+ " LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc2.codeSystemEntityVersionId"; + " LEFT JOIN code_system_entity_version_association cseva1 ON cseva1.codeSystemEntityVersionId1=csc2.versionId" + " LEFT JOIN code_system_entity_version_association cseva2 ON cseva2.codeSystemEntityVersionId2=csc2.versionId"; String sqlCount = "SELECT COUNT(*) FROM code_system_concept csc" + " JOIN code_system_entity_version csev ON csc.codeSystemEntityVersionId=csev.versionId" + " JOIN code_system_entity cse ON csev.versionId=cse.id" + " JOIN code_system_version_entity_membership csvem ON cse.id=csvem.codeSystemEntityId" + " WHERE_TEIL"; /*String sql = " FROM code_system_concept csc" + " JOIN code_system_entity_version csev ON csc.codeSystemEntityVersionId=csev.versionId" + " JOIN code_system_entity cse ON csev.versionId=cse.id" + " JOIN code_system_version_entity_membership csvem ON cse.id=csvem.codeSystemEntityId" + " LEFT JOIN code_system_concept_translation csct ON csct.codeSystemEntityVersionId=csc.codeSystemEntityVersionId";*/ //+ " WHERE csvem.codeSystemVersionId=:codeSystemVersionId" //+ " GROUP BY csc.code" //+ " ORDER BY csc.code"; // Parameter dem Helper hinzufgen // bitte immer den Helper verwenden oder manuell Parameter per Query.setString() hinzufgen, // sonst sind SQL-Injections mglich HQLParameterHelper parameterHelper = new HQLParameterHelper(); parameterHelper.addParameter("", "csvem.codeSystemVersionId", codeSystemVersionId); if (parameter != null && parameter.getCodeSystemEntity() != null) { if (parameter.getCodeSystemEntity().getCodeSystemVersionEntityMemberships() != null && parameter.getCodeSystemEntity().getCodeSystemVersionEntityMemberships().size() > 0) { CodeSystemVersionEntityMembership ms = (CodeSystemVersionEntityMembership) parameter .getCodeSystemEntity().getCodeSystemVersionEntityMemberships().toArray()[0]; parameterHelper.addParameter("csvem.", "isAxis", ms.getIsAxis()); parameterHelper.addParameter("csvem.", "isMainClass", ms.getIsMainClass()); } if (parameter.getCodeSystemEntity().getCodeSystemEntityVersions() != null && parameter.getCodeSystemEntity().getCodeSystemEntityVersions().size() > 0) { CodeSystemEntityVersion csev = (CodeSystemEntityVersion) parameter.getCodeSystemEntity() .getCodeSystemEntityVersions().toArray()[0]; parameterHelper.addParameter("csev.", "statusVisibilityDate", csev.getStatusVisibilityDate()); if (csev.getCodeSystemConcepts() != null && csev.getCodeSystemConcepts().size() > 0) { CodeSystemConcept csc = (CodeSystemConcept) csev.getCodeSystemConcepts().toArray()[0]; parameterHelper.addParameter("csc.", "code", csc.getCode()); parameterHelper.addParameter("csc.", "term", csc.getTerm()); parameterHelper.addParameter("csc.", "termAbbrevation", csc.getTermAbbrevation()); parameterHelper.addParameter("csc.", "isPreferred", csc.getIsPreferred()); if (csc.getCodeSystemConceptTranslations() != null && csc.getCodeSystemConceptTranslations().size() > 0) { CodeSystemConceptTranslation csct = (CodeSystemConceptTranslation) csc .getCodeSystemConceptTranslations().toArray()[0]; parameterHelper.addParameter("csct.", "term", csct.getTerm()); parameterHelper.addParameter("csct.", "termAbbrevation", csct.getTermAbbrevation()); if (csct.getLanguageCd() != null && csct.getLanguageCd().length() > 0) { languageCd = csct.getLanguageCd(); } } } } } /*if(languageCd.length() == 0) sql = sql.replaceAll("AND_LANGUAGE_TERM", ""); else sql = sql.replaceAll("AND_LANGUAGE_TERM", "AND languageCd=:languageCd");*/ if (loggedIn == false) { parameterHelper.addParameter("csev.", "statusVisibility", Definitions.STATUS_CODES.ACTIVE.getCode()); } // Parameter hinzufgen (immer mit AND verbunden) // Gesamt-Anzahl lesen String where = parameterHelper.getWhere(""); //sqlCount = "SELECT COUNT(DISTINCT cse.id) FROM " + sqlCount.replaceAll("WHERE_TEIL", where); sqlCount = sqlCount.replaceAll("WHERE_TEIL", where); //q.addScalar("csc.code", Hibernate.TEXT); // Index: 0 logger.debug("SQL-Count: " + sqlCount); SQLQuery qCount = hb_session.createSQLQuery(sqlCount); parameterHelper.applySQLParameter(qCount); BigInteger anzahlGesamt = (BigInteger) qCount.uniqueResult(); logger.debug("Anzahl Gesamt: " + anzahlGesamt.longValue()); if (anzahlGesamt.longValue() > 0) { // Suche begrenzen int pageSize = -1; int pageIndex = 0; boolean allEntries = false; if (parameter != null && parameter.getPagingParameter() != null) { logger.debug("Search-Parameter angegeben"); if (parameter.getPagingParameter().isAllEntries() != null && parameter.getPagingParameter().isAllEntries().booleanValue() == true) { if (loggedIn) allEntries = true; } if (parameter.getPagingParameter().getPageSize() != null) pageSize = Integer.valueOf(parameter.getPagingParameter().getPageSize()); if (parameter.getPagingParameter().getPageIndex() != null) pageIndex = parameter.getPagingParameter().getPageIndex(); } // MaxResults mit Wert aus SysParam prfen if (traverseConceptsToRoot) { if (pageSize < 0 || (maxPageSizeSearch > 0 && pageSize > maxPageSizeSearch)) pageSize = maxPageSizeSearch; } else { if (pageSize < 0 || (maxPageSize > 0 && pageSize > maxPageSize)) pageSize = maxPageSize; } if (pageIndex < 0) pageIndex = 0; logger.debug("pageIndex: " + pageIndex); logger.debug("pageSize: " + pageSize); /*String sortStr = " ORDER BY csc.code"; if (parameter.getSortingParameter() != null) { if (parameter.getSortingParameter().getSortType() == null || parameter.getSortingParameter().getSortType() == SortingType.SortType.ALPHABETICALLY) { sortStr = " ORDER BY"; if (parameter.getSortingParameter().getSortBy() != null && parameter.getSortingParameter().getSortBy() == SortingType.SortByField.TERM) { sortStr += " csc.term"; } else { sortStr += " csc.code"; } if (parameter.getSortingParameter().getSortDirection() != null && parameter.getSortingParameter().getSortDirection() == SortingType.SortDirection.DESCENDING) { sortStr += " desc"; } } }*/ String sortStr = " ORDER BY code"; if (parameter.getSortingParameter() != null) { if (parameter.getSortingParameter().getSortType() == null || parameter.getSortingParameter() .getSortType() == SortingType.SortType.ALPHABETICALLY) { sortStr = " ORDER BY"; if (parameter.getSortingParameter().getSortBy() != null && parameter .getSortingParameter().getSortBy() == SortingType.SortByField.TERM) { sortStr += " term"; } else { sortStr += " code"; } if (parameter.getSortingParameter().getSortDirection() != null && parameter.getSortingParameter() .getSortDirection() == SortingType.SortDirection.DESCENDING) { sortStr += " desc"; } } } /*String where_all = where + sortStr; if (pageSize > 0 && allEntries == false) { where_all += " LIMIT " + (pageIndex * pageSize) + "," + pageSize; } sql = sql.replaceAll("WHERE_TEIL", where_all);*/ if (pageSize > 0 && allEntries == false) { sortStr += " LIMIT " + (pageIndex * pageSize) + "," + pageSize; } sql = sql.replaceAll("WHERE_TEIL", where); sql += sortStr; int anzahl = 0; //logger.debug("SQL: " + sql); // Query erstellen SQLQuery q = hb_session.createSQLQuery(sql); q.addScalar("csc2.code", StandardBasicTypes.TEXT); // Index: 0 q.addScalar("csc2.term", StandardBasicTypes.TEXT); q.addScalar("csc2.termAbbrevation", StandardBasicTypes.TEXT); q.addScalar("csc2.description", StandardBasicTypes.TEXT); q.addScalar("csc2.isPreferred", StandardBasicTypes.BOOLEAN); q.addScalar("csc2.codeSystemEntityVersionId", StandardBasicTypes.LONG); q.addScalar("csc2.effectiveDate", StandardBasicTypes.TIMESTAMP); // Index: 6 q.addScalar("csc2.insertTimestamp", StandardBasicTypes.TIMESTAMP); q.addScalar("csc2.isLeaf", StandardBasicTypes.BOOLEAN); q.addScalar("csc2.majorRevision", StandardBasicTypes.INTEGER); q.addScalar("csc2.minorRevision", StandardBasicTypes.INTEGER); q.addScalar("csc2.statusVisibility", StandardBasicTypes.INTEGER); q.addScalar("csc2.statusVisibilityDate", StandardBasicTypes.TIMESTAMP); q.addScalar("csc2.versionId", StandardBasicTypes.LONG); q.addScalar("csc2.codeSystemEntityId", StandardBasicTypes.LONG); q.addScalar("csc2.id", StandardBasicTypes.LONG); // Index: 15 q.addScalar("csc2.currentVersionId", StandardBasicTypes.LONG); q.addScalar("csc2.isAxis", StandardBasicTypes.BOOLEAN); // Index: 17 q.addScalar("csc2.isMainClass", StandardBasicTypes.BOOLEAN); q.addScalar("translation_term", StandardBasicTypes.TEXT); // Index: 19 q.addScalar("translation_termAbbrevation", StandardBasicTypes.TEXT); q.addScalar("translation_languageCd", StandardBasicTypes.TEXT); q.addScalar("translation_description", StandardBasicTypes.TEXT); q.addScalar("translation_id", StandardBasicTypes.LONG); q.addScalar("cseva1.codeSystemEntityVersionId1", StandardBasicTypes.LONG); // Index: 24 q.addScalar("cseva1.codeSystemEntityVersionId2", StandardBasicTypes.LONG); q.addScalar("cseva1.leftId", StandardBasicTypes.LONG); q.addScalar("cseva1.associationTypeId", StandardBasicTypes.LONG); q.addScalar("cseva1.associationKind", StandardBasicTypes.INTEGER); q.addScalar("cseva1.status", StandardBasicTypes.INTEGER); q.addScalar("cseva1.statusDate", StandardBasicTypes.TIMESTAMP); q.addScalar("cseva1.insertTimestamp", StandardBasicTypes.TIMESTAMP); q.addScalar("csc2.meaning", StandardBasicTypes.TEXT); //Index: 32 q.addScalar("csc2.hints", StandardBasicTypes.TEXT); q.addScalar("csc2.statusDeactivated", StandardBasicTypes.INTEGER); // Index: 34 q.addScalar("csc2.statusDeactivatedDate", StandardBasicTypes.TIMESTAMP); q.addScalar("csc2.statusWorkflow", StandardBasicTypes.INTEGER); q.addScalar("csc2.statusWorkflowDate", StandardBasicTypes.TIMESTAMP); q.addScalar("cseva2.codeSystemEntityVersionId1", StandardBasicTypes.LONG); // Index: 38 q.addScalar("cseva2.codeSystemEntityVersionId2", StandardBasicTypes.LONG); q.addScalar("cseva2.leftId", StandardBasicTypes.LONG); q.addScalar("cseva2.associationTypeId", StandardBasicTypes.LONG); q.addScalar("cseva2.associationKind", StandardBasicTypes.INTEGER); q.addScalar("cseva2.status", StandardBasicTypes.INTEGER); q.addScalar("cseva2.statusDate", StandardBasicTypes.TIMESTAMP); q.addScalar("cseva2.insertTimestamp", StandardBasicTypes.TIMESTAMP); parameterHelper.applySQLParameter(q); //if(languageCd.length() > 0) q.setString("languageCd", languageCd); response.setCodeSystemEntity(new LinkedList<CodeSystemEntity>()); logger.debug("SQL: " + q.getQueryString()); List conceptList = (List) q.list(); Iterator it = conceptList.iterator(); long lastCodeSystemEntityVersionId = 0; CodeSystemEntity cse = new CodeSystemEntity(); CodeSystemEntityVersion csev = new CodeSystemEntityVersion(); CodeSystemConcept csc = new CodeSystemConcept(); CodeSystemVersionEntityMembership csvem = new CodeSystemVersionEntityMembership(); boolean fertig = false; while (it.hasNext()) { Object[] item = null; long codeSystemEntityVersionId = 0; do { if (it.hasNext() == false) { fertig = true; break; } item = (Object[]) it.next(); // Prfen, ob Translation (1:N) codeSystemEntityVersionId = (Long) item[5]; if (lastCodeSystemEntityVersionId == codeSystemEntityVersionId) { // Gleiches Konzept, Assoziation hinzufgen if (parameter.isLookForward()) addAssociationToEntityVersion(csev, item); } } while (lastCodeSystemEntityVersionId == codeSystemEntityVersionId); if (fertig) break; // Konzepte zusammenbauen cse = new CodeSystemEntity(); csev = new CodeSystemEntityVersion(); csc = new CodeSystemConcept(); csvem = new CodeSystemVersionEntityMembership(); // Konzept if (item[0] != null) csc.setCode(item[0].toString()); if (item[1] != null) csc.setTerm(item[1].toString()); if (item[2] != null) //csc.setTermAbbrevation(new String((char[])item[2])); csc.setTermAbbrevation(item[2].toString()); if (item[3] != null) csc.setDescription(item[3].toString()); if (item[4] != null) csc.setIsPreferred((Boolean) item[4]); if (item[5] != null) csc.setCodeSystemEntityVersionId((Long) item[5]); if (item[32] != null) csc.setMeaning(item[32].toString()); if (item[33] != null) csc.setHints(item[33].toString()); // Entity Version if (item[6] != null) csev.setEffectiveDate(DateHelper.getDateFromObject(item[6])); if (item[7] != null) csev.setInsertTimestamp(DateHelper.getDateFromObject(item[7])); if (item[8] != null) csev.setIsLeaf((Boolean) item[8]); if (item[9] != null) csev.setMajorRevision((Integer) item[9]); if (item[10] != null) csev.setMinorRevision((Integer) item[10]); if (item[11] != null) csev.setStatusVisibility((Integer) item[11]); if (item[12] != null) csev.setStatusVisibilityDate(DateHelper.getDateFromObject(item[12])); if (item[13] != null) csev.setVersionId((Long) item[13]); if (item[34] != null) csev.setStatusDeactivated((Integer) item[34]); if (item[35] != null) csev.setStatusDeactivatedDate(DateHelper.getDateFromObject(item[35])); if (item[36] != null) csev.setStatusWorkflow((Integer) item[36]); if (item[37] != null) csev.setStatusWorkflowDate(DateHelper.getDateFromObject(item[37])); // Code System Entity if (item[15] != null) cse.setId((Long) item[15]); if (item[16] != null) cse.setCurrentVersionId((Long) item[16]); // Entity Membership if (item[17] != null) csvem.setIsAxis((Boolean) item[17]); if (item[18] != null) csvem.setIsMainClass((Boolean) item[18]); // Translation addTranslationToConcept(csc, item); // Assoziation if (parameter.isLookForward()) addAssociationToEntityVersion(csev, item); if (traverseConceptsToRoot) { // Alle Elemente bis zum Root ermitteln (fr Suche) TraverseConceptToRoot traverse = new TraverseConceptToRoot(); TraverseConceptToRootRequestType requestTraverse = new TraverseConceptToRootRequestType(); requestTraverse.setLoginToken(parameter.getLoginToken()); requestTraverse.setCodeSystemEntity(new CodeSystemEntity()); CodeSystemEntityVersion csevRequest = new CodeSystemEntityVersion(); csevRequest.setVersionId(csev.getVersionId()); requestTraverse.getCodeSystemEntity() .setCodeSystemEntityVersions(new HashSet<CodeSystemEntityVersion>()); requestTraverse.getCodeSystemEntity().getCodeSystemEntityVersions().add(csevRequest); requestTraverse.setDirectionToRoot(true); //TraverseConceptToRootResponseType responseTraverse = traverse.TraverseConceptToRoot(requestTraverse, hb_session); // die Session bergeben, damit diese nicht geschlossen wird TraverseConceptToRootResponseType responseTraverse = traverse .TraverseConceptToRoot(requestTraverse, null); //logger.debug("responseTraverse: " + responseTraverse.getReturnInfos().getMessage()); if (responseTraverse.getReturnInfos().getStatus() == ReturnType.Status.OK) { if (csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1() == null) { csev.setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1( responseTraverse.getCodeSystemEntityVersionRoot() .getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1()); } else { csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1() .addAll(responseTraverse.getCodeSystemEntityVersionRoot() .getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1()); } } } if (parameter.isLoadMetadata() != null && parameter.isLoadMetadata().booleanValue()) { String hql = "from CodeSystemMetadataValue mv " + " join fetch mv.metadataParameter mp " + " where codeSystemEntityVersionId=:csev_id"; Query query = hb_session.createQuery(hql); query.setLong("csev_id", csev.getVersionId()); csev.setCodeSystemMetadataValues(new HashSet<CodeSystemMetadataValue>(query.list())); // remove circle problems for (CodeSystemMetadataValue mv : csev.getCodeSystemMetadataValues()) { mv.setCodeSystemEntityVersion(null); mv.getMetadataParameter().setCodeSystem(null); mv.getMetadataParameter().setValueSet(null); mv.getMetadataParameter().setValueSetMetadataValues(null); mv.getMetadataParameter().setCodeSystemMetadataValues(null); mv.getMetadataParameter().setDescription(null); mv.getMetadataParameter().setMetadataParameterType(null); } } if (parameter.isLoadTranslation() != null && parameter.isLoadTranslation().booleanValue()) { String hql = "from CodeSystemConceptTranslation csct " + " where codeSystemEntityVersionId=:csev_id"; //+ " order by csct.languageCd"; Query query = hb_session.createQuery(hql); query.setLong("csev_id", csev.getVersionId()); csc.setCodeSystemConceptTranslations( new HashSet<CodeSystemConceptTranslation>(query.list())); // remove circle problems for (CodeSystemConceptTranslation trans : csc.getCodeSystemConceptTranslations()) { trans.setCodeSystemConcept(null); } } //logger.debug(csc.getCode()); //logger.debug("Type: " + csc.getClass().getCanonicalName()); /*Object[] o = (Object[]) csc; for(int i=0;i<o.length;++i) { //logger.debug(i + ": " + o.toString()); if(o[i] != null) { logger.debug(i + ": " + o[i].toString()); logger.debug(i + ": " + o[i].getClass().getCanonicalName()); } else logger.debug(i + ": null"); //for(int j=0;j<) }*/ csev.setCodeSystemConcepts(new HashSet<CodeSystemConcept>()); csev.getCodeSystemConcepts().add(csc); cse.setCodeSystemEntityVersions(new HashSet<CodeSystemEntityVersion>()); cse.getCodeSystemEntityVersions().add(csev); cse.setCodeSystemVersionEntityMemberships(new HashSet<CodeSystemVersionEntityMembership>()); cse.getCodeSystemVersionEntityMemberships().add(csvem); response.getCodeSystemEntity().add(cse); lastCodeSystemEntityVersionId = codeSystemEntityVersionId; anzahl++; } // Treffermenge prfen // Paging wird aktiviert if (anzahlGesamt.longValue() > maxPageSize) { response.setPagingInfos(new PagingResultType()); response.getPagingInfos().setMaxPageSize(maxPageSize); response.getPagingInfos().setPageIndex(pageIndex); response.getPagingInfos().setPageSize(String.valueOf(pageSize)); response.getPagingInfos().setCount(anzahlGesamt.intValue()); if (parameter != null && parameter.getPagingParameter() != null) { response.getPagingInfos().setMessage( "Paging wurde aktiviert, da die Treffermenge grer ist als die maximale Seitengre."); } } else { if ((maxPageSizeUserSpecific != -1) && anzahlGesamt.longValue() > maxPageSizeUserSpecific) { response.setPagingInfos(new PagingResultType()); response.getPagingInfos().setMaxPageSize(maxPageSizeUserSpecific); response.getPagingInfos().setPageIndex(pageIndex); response.getPagingInfos().setPageSize(String.valueOf(maxPageSizeUserSpecific)); response.getPagingInfos().setCount(anzahlGesamt.intValue()); if (parameter != null && parameter.getPagingParameter() != null) { response.getPagingInfos().setMessage( "Paging wurde aktiviert, da popUpSearchCS spezifische Seitenanzahl."); } } } // Status an den Aufrufer weitergeben response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO); response.getReturnInfos().setStatus(ReturnType.Status.OK); response.getReturnInfos().setMessage("Konzepte erfolgreich gelesen, Anzahl: " + anzahl); response.getReturnInfos().setCount(anzahl); } else { response.setCodeSystemEntity(new LinkedList<CodeSystemEntity>()); response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO); response.getReturnInfos().setStatus(ReturnType.Status.OK); response.getReturnInfos().setMessage("Keine Konzepte fr die Filterkriterien vorhanden"); response.getReturnInfos().setCount(0); } /*String hql = "select distinct csc from CodeSystemConcept csc"; hql += " join fetch csc.codeSystemEntityVersion csev"; hql += " join fetch csev.codeSystemEntity cse"; hql += " left outer join fetch csc.codeSystemConceptTranslations csct"; hql += " join fetch cse.codeSystemVersionEntityMemberships csvem"; //if (parameter.isLookForward()) //{ // hql += " join fetch csev.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1 ass1"; // hql += " join fetch csev.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2 ass2"; //} // Parameter dem Helper hinzufgen // bitte immer den Helper verwenden oder manuell Parameter per Query.setString() hinzufgen, // sonst sind SQL-Injections mglich HQLParameterHelper parameterHelper = new HQLParameterHelper(); parameterHelper.addParameter("", "codeSystemVersionId", codeSystemVersionId); if (parameter != null && parameter.getCodeSystemEntity() != null) { if (parameter.getCodeSystemEntity().getCodeSystemVersionEntityMemberships() != null && parameter.getCodeSystemEntity().getCodeSystemVersionEntityMemberships().size() > 0) { CodeSystemVersionEntityMembership ms = (CodeSystemVersionEntityMembership) parameter.getCodeSystemEntity().getCodeSystemVersionEntityMemberships().toArray()[0]; parameterHelper.addParameter("csvem.", "isAxis", ms.getIsAxis()); parameterHelper.addParameter("csvem.", "isMainClass", ms.getIsMainClass()); } if (parameter.getCodeSystemEntity().getCodeSystemEntityVersions() != null && parameter.getCodeSystemEntity().getCodeSystemEntityVersions().size() > 0) { CodeSystemEntityVersion csev = (CodeSystemEntityVersion) parameter.getCodeSystemEntity().getCodeSystemEntityVersions().toArray()[0]; parameterHelper.addParameter("csev.", "statusDate", csev.getStatusDate()); if (csev.getCodeSystemConcepts() != null && csev.getCodeSystemConcepts().size() > 0) { CodeSystemConcept csc = (CodeSystemConcept) csev.getCodeSystemConcepts().toArray()[0]; parameterHelper.addParameter("csc.", "code", csc.getCode()); parameterHelper.addParameter("csc.", "term", csc.getTerm()); parameterHelper.addParameter("csc.", "termAbbrevation", csc.getTermAbbrevation()); parameterHelper.addParameter("csc.", "isPreferred", csc.getIsPreferred()); if (csc.getCodeSystemConceptTranslations() != null && csc.getCodeSystemConceptTranslations().size() > 0) { CodeSystemConceptTranslation csct = (CodeSystemConceptTranslation) csc.getCodeSystemConceptTranslations().toArray()[0]; parameterHelper.addParameter("csct.", "term", csct.getTerm()); parameterHelper.addParameter("csct.", "termAbbrevation", csct.getTermAbbrevation()); if (csct.getLanguageId() > 0) parameterHelper.addParameter("csct.", "languageId", csct.getLanguageId()); } } } } if (loggedIn == false) { parameterHelper.addParameter("csev.", "status", Definitions.STATUS_CODES.ACTIVE.getCode()); } // Parameter hinzufgen (immer mit AND verbunden) String where = parameterHelper.getWhere(""); hql += where; // immer neueste Version lesen hql += " AND csev.id=cse.currentVersionId"; hql += " ORDER BY csc.code"; // Suche begrenzen int pageSize = -1; int pageIndex = 0; boolean allEntries = false; if (parameter != null && parameter.getPagingParameter() != null) { // vorher aber noch die Gesamtanzahl berechnen //Integer count = (Integer) hb_session.createQuery("select count(*) from ....").uniqueResult(); if (parameter.getPagingParameter().isAllEntries() != null && parameter.getPagingParameter().isAllEntries().booleanValue() == true) { if (loggedIn) allEntries = true; } pageSize = parameter.getPagingParameter().getPageSize(); pageIndex = parameter.getPagingParameter().getPageIndex(); } // MaxResults mit Wert aus SysParam prfen if (traverseConceptsToRoot) { if (pageSize < 0 || (maxPageSizeSearch > 0 && pageSize > maxPageSizeSearch)) pageSize = maxPageSizeSearch; } else { if (pageSize < 0 || (maxPageSize > 0 && pageSize > maxPageSize)) pageSize = maxPageSize; } if (pageIndex < 0) pageIndex = 0; // Gesamt-Anzahl lesen String hqlCount = "select count(term) from CodeSystemConcept csc"; hqlCount += " join csc.codeSystemEntityVersion csev"; hqlCount += " join csev.codeSystemEntity cse"; hqlCount += " join cse.codeSystemVersionEntityMemberships csvem"; hqlCount += where; //hql = hql.replace("distinct csc", "count(term)"); logger.debug("HQL-Count: " + hqlCount); org.hibernate.Query q = hb_session.createQuery(hqlCount); // Die Parameter knnen erst hier gesetzt werden (bernimmt Helper) parameterHelper.applyParameter(q); long anzahlGesamt = (Long) q.uniqueResult(); // Anzahl zhlen Datenbank-Aufruf durchfhren //int anzahlGesamt = q.list().size(); //int anzahlGesamt = 100; // TODO Gesamt-Anzahl herausbekommen logger.debug("Anzahl Gesamt: " + anzahlGesamt); logger.debug("HQL: " + hql); // Query erstellen q = hb_session.createQuery(hql); // Die Parameter knnen erst hier gesetzt werden (bernimmt Helper) parameterHelper.applyParameter(q); //conceptList = (java.util.List<CodeSystemConcept>) q.list(); if (anzahlGesamt > 0) { //hb_session.setFlushMode(FlushMode.AUTO); ScrollableResults scrollResults = q.scroll(); int itCount = 0; if (scrollResults != null) { java.util.List<CodeSystemEntity> entityList = new LinkedList<CodeSystemEntity>(); if (pageIndex > 0 && allEntries == false && anzahlGesamt > 0) { // Vorspulen //if(pageSize * pageIndex < anzahlGesamt) // scrollResults.setRowNumber(pageSize * pageIndex); for (int i = 0; i < pageSize * pageIndex && i < anzahlGesamt; ++i) { if (scrollResults.next() == false) break; if (i % 50 == 0) { // wichtig, da Speicher sonst voll luft hb_session.flush(); hb_session.clear(); } } } //Iterator<CodeSystemConcept> iterator = conceptList.iterator(); //while (iterator.hasNext()) try { while (scrollResults.next()) { if (itCount >= pageSize && allEntries == false) break; if (itCount % 50 == 0) { // wichtig, da Speicher sonst voll luft //hb_session.flush(); hb_session.clear(); } itCount++; //CodeSystemConcept csc = iterator.next(); CodeSystemConcept csc = (CodeSystemConcept) scrollResults.get(0); // neues Entity generieren, damit nicht nachgeladen werden muss CodeSystemEntity entity = csc.getCodeSystemEntityVersion().getCodeSystemEntity(); CodeSystemEntityVersion csev = csc.getCodeSystemEntityVersion(); csev.setCodeSystemEntity(null); if (parameter.isLookForward()) { // Verbindungen suchen if (csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2() != null) { for (CodeSystemEntityVersionAssociation ass : csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2()) { ass.setCodeSystemEntityVersionByCodeSystemEntityVersionId1(null); ass.setCodeSystemEntityVersionByCodeSystemEntityVersionId2(null); ass.setAssociationType(null); } } if (csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1() != null) { for (CodeSystemEntityVersionAssociation ass : csev.getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1()) { ass.setCodeSystemEntityVersionByCodeSystemEntityVersionId1(null); ass.setCodeSystemEntityVersionByCodeSystemEntityVersionId2(null); ass.setAssociationType(null); } } } else { if (traverseConceptsToRoot) { // Alle Elemente bis zum Root ermitteln (fr Suche) TraverseConceptToRoot traverse = new TraverseConceptToRoot(); TraverseConceptToRootRequestType requestTraverse = new TraverseConceptToRootRequestType(); requestTraverse.setLoginToken(parameter.getLoginToken()); requestTraverse.setCodeSystemEntity(new CodeSystemEntity()); CodeSystemEntityVersion csevRequest = new CodeSystemEntityVersion(); csevRequest.setVersionId(csev.getVersionId()); requestTraverse.getCodeSystemEntity().setCodeSystemEntityVersions(new HashSet<CodeSystemEntityVersion>()); requestTraverse.getCodeSystemEntity().getCodeSystemEntityVersions().add(csevRequest); requestTraverse.setDirectionToRoot(true); requestTraverse.setReadEntityDetails(false); TraverseConceptToRootResponseType responseTraverse = traverse.TraverseConceptToRoot(requestTraverse, hb_session); // die Session bergeben, damit diese nicht geschlossen wird //logger.debug("responseTraverse: " + responseTraverse.getReturnInfos().getMessage()); if (responseTraverse.getReturnInfos().getStatus() == ReturnType.Status.OK) { csev.setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1( responseTraverse.getCodeSystemEntityVersionRoot().getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1()); } else { csev.setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1(null); } } else { csev.setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1(null); } csev.setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2(null); } csev.setCodeSystemMetadataValues(null); csev.setConceptValueSetMemberships(null); csev.setPropertyVersions(null); csev.setAssociationTypes(null); csc.setCodeSystemEntityVersion(null); logger.debug("Akt Code: " + csc.getCode() + ", " + csc.getTerm()); //Translations if (csc.getCodeSystemConceptTranslations() != null) { Iterator<CodeSystemConceptTranslation> itTrans = csc.getCodeSystemConceptTranslations().iterator(); while (itTrans.hasNext()) { CodeSystemConceptTranslation csct = itTrans.next(); csct.setCodeSystemConcept(null); } } csev.setCodeSystemConcepts(new HashSet<CodeSystemConcept>()); csev.getCodeSystemConcepts().add(csc); entity.setCodeSystemEntityVersions(new HashSet<CodeSystemEntityVersion>()); entity.getCodeSystemEntityVersions().add(csev); // M:N Verbindung zur Vokabular-Version (ohne nachladen) CodeSystemVersionEntityMembership ms = (CodeSystemVersionEntityMembership) entity.getCodeSystemVersionEntityMemberships().toArray()[0]; ms.setCodeSystemVersion(null); ms.setCodeSystemEntity(null); ms.setId(null); entity.setCodeSystemVersionEntityMemberships(new HashSet<CodeSystemVersionEntityMembership>()); entity.getCodeSystemVersionEntityMemberships().add(ms); entityList.add(entity); } } catch (org.hibernate.exception.GenericJDBCException ex) { logger.debug("Keine Eintraege"); ex.printStackTrace(); } int anzahl = 0; if (entityList != null) anzahl = entityList.size(); response.setCodeSystemEntity(entityList); // Treffermenge prfen if (anzahlGesamt > anzahl) { // Paging wird aktiviert response.setPagingInfos(new PagingResultType()); response.getPagingInfos().setMaxPageSize(maxPageSize); response.getPagingInfos().setPageIndex(pageIndex); response.getPagingInfos().setPageSize(pageSize); response.getPagingInfos().setCount((int) anzahlGesamt); if (parameter != null && parameter.getPagingParameter() != null) { response.getPagingInfos().setMessage("Paging wurde aktiviert, da die Treffermenge grer ist als die maximale Seitengre."); } //response.getPagingInfos().setMessage(); } //response.setPagingInfos(null); // Status an den Aufrufer weitergeben response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO); response.getReturnInfos().setStatus(ReturnType.Status.OK); response.getReturnInfos().setMessage("Konzepte erfolgreich gelesen, Anzahl: " + anzahl); response.getReturnInfos().setCount(anzahl); } } else { response.setCodeSystemEntity(new LinkedList<CodeSystemEntity>()); response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO); response.getReturnInfos().setStatus(ReturnType.Status.OK); response.getReturnInfos().setMessage("Keine Konzepte fr die Filterkriterien vorhanden"); response.getReturnInfos().setCount(0); }*/ // Hibernate-Block wird in 'finally' geschlossen, erst danach // Auswertung der Daten // Achtung: hiernach knnen keine Tabellen/Daten mehr nachgeladen werden //if(createHibernateSession) //hb_session.getTransaction().commit(); } catch (Exception e) { //if(createHibernateSession) //hb_session.getTransaction().rollback(); // Fehlermeldung an den Aufrufer weiterleiten response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos() .setMessage("Fehler bei 'ListCodeSystemConcepts', Hibernate: " + e.getLocalizedMessage()); LoggingOutput.outputException(e, this); } finally { // Transaktion abschlieen if (createHibernateSession) { hb_session.close(); } } } catch (Exception e) { // Fehlermeldung an den Aufrufer weiterleiten response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos().setMessage("Fehler bei 'ListCodeSystemConcepts': " + e.getLocalizedMessage()); LoggingOutput.outputException(e, this); } return response; }
From source file:de.fhdo.terminologie.ws.search.ListCodeSystems.java
License:Apache License
/** * Listet Vokabulare des Terminologieservers auf * /*from w w w. j a va 2s . c o m*/ * @param parameter Die Parameter des Webservices * @return Ergebnis des Webservices, alle gefundenen Vokabulare mit angegebenen Filtern */ public ListCodeSystemsResponseType ListCodeSystems(ListCodeSystemsRequestType parameter, String ipAddress) { if (logger.isInfoEnabled()) logger.info("====== ListCodeSystems gestartet ======"); // Return-Informationen anlegen ListCodeSystemsResponseType response = new ListCodeSystemsResponseType(); response.setReturnInfos(new ReturnType()); // Parameter prfen if (validateParameter(parameter, response) == false) { return response; // Fehler bei den Parametern } // Login-Informationen auswerten (gilt fr jeden Webservice) boolean loggedIn = false; boolean isAdmin = false; AuthenticateInfos loginInfoType = null; if (parameter != null && parameter.getLoginToken() != null) { loginInfoType = Authorization.authenticate(ipAddress, parameter.getLoginToken()); loggedIn = loginInfoType.isLoggedIn(); if (loggedIn) isAdmin = loginInfoType.isIsAdmin(); } if (logger.isDebugEnabled()) logger.debug("Benutzer ist eingeloggt: " + loggedIn); try { java.util.List<CodeSystem> list = null; // Hibernate-Block, Session ffnen org.hibernate.Session hb_session = HibernateUtil.getSessionFactory().openSession(); //hb_session.getTransaction().begin(); try // 2. try-catch-Block zum Abfangen von Hibernate-Fehlern { // HQL erstellen String hql = "select distinct cs from CodeSystem cs"; hql += " join fetch cs.codeSystemVersions csv"; if (loggedIn) { hql += " left outer join csv.licencedUsers lu"; } // Parameter dem Helper hinzufgen // bitte immer den Helper verwenden oder manuell Parameter per Query.setString() hinzufgen, // sonst sind SQL-Injections mglich HQLParameterHelper parameterHelper = new HQLParameterHelper(); if (parameter != null && parameter.getCodeSystem() != null) { // Hier alle Parameter aus der Cross-Reference einfgen // addParameter(String Prefix, String DBField, Object Value) parameterHelper.addParameter("cs.", "name", parameter.getCodeSystem().getName()); parameterHelper.addParameter("cs.", "description", parameter.getCodeSystem().getDescription()); parameterHelper.addParameter("cs.", "insertTimestamp", parameter.getCodeSystem().getInsertTimestamp()); // z.B. '2011-09-26T15:40:00' if (parameter.getCodeSystem().getCodeSystemVersions() != null && parameter.getCodeSystem().getCodeSystemVersions().size() > 0) { CodeSystemVersion csv = (CodeSystemVersion) parameter.getCodeSystem() .getCodeSystemVersions().toArray()[0]; parameterHelper.addParameter("csv.", "description", csv.getDescription()); parameterHelper.addParameter("csv.", "expiredDate", csv.getExpirationDate()); parameterHelper.addParameter("csv.", "insertTimestamp", csv.getInsertTimestamp()); parameterHelper.addParameter("csv.", "description", csv.getLicenceHolder()); parameterHelper.addParameter("csv.", "name", csv.getName()); parameterHelper.addParameter("csv.", "oid", csv.getOid()); parameterHelper.addParameter("csv.", "preferredLanguageCd", csv.getPreferredLanguageCd()); parameterHelper.addParameter("csv.", "releaseDate", csv.getReleaseDate()); parameterHelper.addParameter("csv.", "source", csv.getSource()); parameterHelper.addParameter("csv.", "underLicence", csv.getUnderLicence()); parameterHelper.addParameter("csv.", "validityRange", csv.getValidityRange()); if (loggedIn) // nur mglich, wenn eingeloggt parameterHelper.addParameter("csv.", "status", csv.getStatus()); } } // hier: immer nur aktive Vokabulare abrufen if (isAdmin == false) parameterHelper.addParameter("csv.", "status", Definitions.STATUS_CODES.ACTIVE.getCode()); if (loggedIn == false) { // ohne Login keine Vokabulare mit Lizenzen abrufen parameterHelper.addParameter("csv.", "underLicence", 0); } // Parameter hinzufgen (immer mit AND verbunden) String where = parameterHelper.getWhere(""); hql += where; if (loggedIn) { // jetzt auf eine gltige Lizenz prfen // muss manuell hinzugefgt werden (fr Helper zu komplex, wg. OR) logger.debug("WHERE: " + where); if (where.length() > 2) hql += " AND "; else hql += " WHERE "; hql += " (csv.underLicence = 0 OR "; hql += " (lu.validFrom < '" + HQLParameterHelper.getSQLDateStr(new java.util.Date()) + "'"; hql += " AND lu.validTo > '" + HQLParameterHelper.getSQLDateStr(new java.util.Date()) + "'"; hql += " AND lu.id.codeSystemVersionId=csv.versionId"; hql += " AND lu.id.userId=" + loginInfoType.getUserId(); hql += " ))"; } hql += " ORDER BY cs.name, csv.name"; // Query erstellen org.hibernate.Query q = hb_session.createQuery(hql); // Die Parameter knnen erst hier gesetzt werden (bernimmt Helper) parameterHelper.applyParameter(q); logger.debug("Query: " + q.getQueryString()); // Datenbank-Aufruf durchfhren list = (java.util.List<CodeSystem>) q.list(); // Hibernate-Block wird in 'finally' geschlossen, erst danach // Auswertung der Daten // Achtung: hiernach knnen keine Tabellen/Daten mehr nachgeladen werden } catch (Exception e) { //hb_session.getTransaction().rollback(); // Fehlermeldung an den Aufrufer weiterleiten response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos() .setMessage("Fehler bei 'ListCodeSystems', Hibernate: " + e.getLocalizedMessage()); logger.error("Fehler bei 'ListCodeSystems', Hibernate: " + e.getLocalizedMessage()); } finally { hb_session.close(); } // Ergebnis auswerten // Spter wird die Klassenstruktur von Jaxb in die XML-Struktur umgewandelt // dafr mssen nichtbentigte Beziehungen gelscht werden (auf null setzen) if (list != null) { Iterator<CodeSystem> iterator = list.iterator(); while (iterator.hasNext()) { CodeSystem cs = iterator.next(); //logger.debug("CS: " + cs.getName()); if (cs.getCodeSystemVersions() != null) { Iterator<CodeSystemVersion> iteratorVV = cs.getCodeSystemVersions().iterator(); while (iteratorVV.hasNext()) { CodeSystemVersion csv = iteratorVV.next(); //logger.debug("CSV: " + csv.getName()); //logger.debug("ValidityRange: " + csv.getValidityRange()); // Nicht anzuzeigende Beziehungen null setzen csv.setLicenceTypes(null); csv.setLicencedUsers(null); csv.setCodeSystemVersionEntityMemberships(null); csv.setCodeSystem(null); } } cs.setDomainValues(null); // Keine zugehrigen Domnen zurckgeben cs.setMetadataParameters(null); // bereinigte Liste der Antwort beifgen response.setCodeSystem(list); response.getReturnInfos().setCount(list.size()); } // Status an den Aufrufer weitergeben response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.INFO); response.getReturnInfos().setStatus(ReturnType.Status.OK); response.getReturnInfos().setMessage("CodeSysteme erfolgreich gelesen"); } } catch (Exception e) { // Fehlermeldung an den Aufrufer weiterleiten response.getReturnInfos().setOverallErrorCategory(ReturnType.OverallErrorCategory.ERROR); response.getReturnInfos().setStatus(ReturnType.Status.FAILURE); response.getReturnInfos().setMessage("Fehler bei 'ListCodeSystems': " + e.getLocalizedMessage()); logger.error("Fehler bei 'ListCodeSystems': " + e.getLocalizedMessage()); } return response; }
From source file:edu.harvard.med.screensaver.db.ScreenDAOImpl.java
License:Open Source License
@Override public int populateStudyReagentLinkTable(final int screenId) { final int[] result = new int[1]; _dao.runQuery(new edu.harvard.med.screensaver.db.Query() { public List<?> execute(Session session) { String sql = "insert into study_reagent_link " + "(study_id,reagent_id) " + "select :studyId as study_id, " + "reagent_id from " + "(select distinct(reagent_id) " + "from reagent " + "join annotation_value using(reagent_id) " + "join annotation_type using(annotation_type_id) " + "where study_id = :studyId ) a"; log.debug("sql: " + sql); Query query = session.createSQLQuery(sql); query.setParameter("studyId", screenId); int rows = query.executeUpdate(); if (rows == 0) { log.warn("No rows were updated: " + query.getQueryString()); }/*from w ww. j av a 2 s. co m*/ log.info("study_reagent_link updated: " + rows); result[0] = rows; return null; } }); return result[0]; }
From source file:edu.sjsu.cmpe275.lab2.model.HibernateUtil.java
License:Open Source License
public static void main(final String[] args) throws Exception { Session session = getSessionFactory().openSession(); try {// ww w . j a v a2 s .c om System.out.println("querying all the managed entities..."); final Map metadataMap = session.getSessionFactory().getAllClassMetadata(); for (Object key : metadataMap.keySet()) { final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key); final String entityName = classMetadata.getEntityName(); final Query query = session.createQuery("from " + entityName); System.out.println("executing: " + query.getQueryString()); for (Object o : query.list()) { System.out.println(" " + o); } } } finally { session.close(); } }
From source file:es.pode.auditoria.negocio.dominio.BusquedaDaoImpl.java
License:Open Source License
public java.util.List listarTerminosBuscadosDesdeHasta(final int transform, final java.lang.String queryString, java.util.Calendar fechaDesde, java.util.Calendar fechaHasta) { try {/*from www.j a v a 2 s .co m*/ logger.info("BUSQUEDADAOIMPL listarTerminosBuscadosDesdeHasta"); org.hibernate.Query queryObject = super.getSession(false).createQuery(queryString); logger.info("queryObject " + queryObject); queryObject.setParameter("fechaHasta", fechaHasta); queryObject.setParameter("fechaDesde", fechaDesde); logger.info("listarTerminosBuscadosDesdeHasta[" + queryObject.getQueryString() + "]"); java.util.List results = queryObject.list(); transformEntities(transform, results); return results; } catch (org.hibernate.HibernateException ex) { throw super.convertHibernateAccessException(ex); } }
From source file:es.pode.auditoria.negocio.dominio.OperacionDaoImpl.java
License:Open Source License
public Object obtenerNumOperacionesDesdeHasta(final int transform, final java.lang.String queryString, final Calendar fechaDesde, final Calendar fechaHasta, final java.lang.String operacion) { logger.info("obtenerNumOperacionesDesdeHasta"); try {//from w ww . j a va2 s. c om org.hibernate.Query queryObject = super.getSession(false).createQuery(queryString); queryObject.setParameter("fechaDesde", fechaDesde); queryObject.setParameter("fechaHasta", fechaHasta); queryObject.setParameter("operacion", operacion); logger.info("despues de asignar los parametros"); logger.info("fechaDesde " + fechaDesde); logger.info("fechaHasta " + fechaHasta); logger.info("operacion " + operacion); logger.info("queryObject.getQueryString() " + queryObject.getQueryString()); java.util.List results = queryObject.list(); logger.info("results vale " + results); Object result = null; if (results != null) { if (results.size() > 1) { throw new org.springframework.dao.InvalidDataAccessResourceUsageException( "More than one instance of 'java.lang.Integer" + "' was found when executing query --> '" + queryString + "'"); } else if (results.size() == 1) { logger.info("tamanio 1"); result = (Long) results.iterator().next(); logger.info("result vale " + result); } } logger.info("result vale " + result); result = transformEntity(transform, (Long) result); return result; } catch (org.hibernate.HibernateException ex) { throw super.convertHibernateAccessException(ex); } }
From source file:es.pode.auditoria.negocio.dominio.ValoracionDaoImpl.java
License:Open Source License
public List listarODEsValoradosDesdeHasta(int transform, String queryString, Date fechaDesde, Date fechaHasta) { try {/*from ww w. j a v a2 s.co m*/ org.hibernate.Query queryObject = super.getSession(false).createQuery(queryString); queryObject.setParameter("fechaHasta", fechaHasta); queryObject.setParameter("fechaDesde", fechaDesde); logger.debug("listarODEsValoradosDesdeHasta[" + queryObject.getQueryString() + "]"); java.util.List results = queryObject.list(); transformEntities(transform, results); return results; } catch (org.hibernate.HibernateException ex) { throw super.convertHibernateAccessException(ex); } }
From source file:gg.db.datamodel.Datamodel.java
License:Open Source License
/** * Gets a query object/*from w w w .j av a 2 s . c o m*/ * @param session Database session * @param searchCriteria Search criteria * @param searchFromStartDate Search from start? (if false, no filter on start date) * @param searchUntilEndDate Search until end? (if false, no filter on end date) * @param filterOnCategories Filter on categories? * @param select Select statement * @param where Where statement * @param groupBy Group by statement * @return Query object */ private static Query getQuery(Session session, SearchCriteria searchCriteria, boolean searchFromStartDate, boolean searchUntilEndDate, boolean filterOnCategories, boolean filterOnPayees, boolean filterOnKeywords, String select, String where, String groupBy) { log.entering(CLASS_NAME, "getQuery", new Object[] { searchCriteria, searchFromStartDate, searchUntilEndDate, filterOnCategories, filterOnPayees, filterOnKeywords, select, where, groupBy }); if (searchCriteria == null) { throw new IllegalArgumentException("The parameter 'searchCriteria' is null"); } Category transferCategory = getCategory(Category.TRANSFER.getGrisbiCategoryId(), Category.TRANSFER.getGrisbiSubCategoryId()); String queryString = ""; // SELECT clause if (select != null) { queryString = select + " "; } // FROM clause String fromClause = "from Transaction t inner join t.account as a"; // WHERE clause List<String> whereClause = new ArrayList<String>(); whereClause.add("a.active=true"); if (searchCriteria.hasAccountsFilter()) { whereClause.add("t.account in (:accounts)"); } else if (searchCriteria.hasCurrencyFilter()) { whereClause.add("a.currency=:currency"); } whereClause.add("t.parentTransaction is null"); if (where != null) { whereClause.add(where); } if (searchCriteria.hasPeriodFilter() && searchFromStartDate) { whereClause.add("t.date>=:start"); } if (searchCriteria.hasPeriodFilter() && searchUntilEndDate) { whereClause.add("t.date<=:end"); } if (searchCriteria.hasCategoriesFilter() && filterOnCategories) { whereClause.add("t.category in (:categories)"); } if (searchCriteria.hasPayeesFilter() && filterOnPayees) { whereClause.add("t.payee in (:payees)"); } if (!searchCriteria.isIncludeTransferTransactions()) { whereClause.add("t.category<>:categoryTransfer"); } if (searchCriteria.hasKeywordsFilter() && filterOnKeywords) { whereClause.add("upper(t.comment) like :keyword"); } // Compute the WHERE statement queryString += fromClause; if (whereClause.size() > 0) { queryString += " where "; } Iterator<String> it = whereClause.iterator(); String whereItem; while (it.hasNext()) { whereItem = it.next(); queryString += whereItem; if (it.hasNext()) { queryString += " and "; } } // Group by statement queryString += " " + groupBy; // Create query Query query = session.createQuery(queryString); // Add the entities to the query if (searchCriteria.hasAccountsFilter()) { query.setParameterList("accounts", searchCriteria.getAccounts()); } else if (searchCriteria.hasCurrencyFilter()) { query.setParameter("currency", searchCriteria.getCurrency()); } if (searchCriteria.hasPeriodFilter() && searchFromStartDate) { query.setParameter("start", searchCriteria.getPeriod().getStart()); } if (searchCriteria.hasPeriodFilter() && searchUntilEndDate) { query.setParameter("end", searchCriteria.getPeriod().getEnd()); } if (searchCriteria.hasCategoriesFilter() && filterOnCategories) { query.setParameterList("categories", searchCriteria.getCategories()); } if (searchCriteria.hasPayeesFilter() && filterOnPayees) { query.setParameterList("payees", searchCriteria.getPayees()); } if (!searchCriteria.isIncludeTransferTransactions()) { query.setParameter("categoryTransfer", transferCategory); } if (searchCriteria.hasKeywordsFilter() && filterOnKeywords) { query.setParameter("keyword", "%" + searchCriteria.getKeywords().toUpperCase() + "%"); } log.exiting(CLASS_NAME, "getQuery", query.getQueryString()); return query; }
From source file:gov.nih.nci.system.dao.impl.orm.ORMDAOImpl.java
License:Open Source License
/** * Return the resultset of the query embedded in an object of gov.nih.nci.common.net.Response * @param request - a gov.nih.nci.common.net.Request object passed from client * @return an object of gov.nih.nci.common.net.Response that contains the query resultset * @throws DAOException//from w w w .j a va2 s.c om */ public Response query(Request request) throws DAOException { List rs = null; int counter = 0; ORMConnection ormConn = ORMConnection.getInstance(); org.hibernate.Session session = null; Criteria hCriteria = null; Integer rowCount = null; Query query = null; String entityName = request.getDomainObjectName(); ServiceLocator serviceLocator = null; try { serviceLocator = (ServiceLocator) ObjectFactory.getObject("ServiceLocator"); counter = serviceLocator.getORMCounter(entityName); session = ORMConnection.openSession(entityName); } catch (Exception e) { log.error("Could not retrieve proper datasource \n " + e.getMessage()); throw new DAOException("Could not retrieve proper datasource " + e); } Object obj = request.getRequest(); Integer firstRow = request.getFirstRow(); log.debug("Integer firstRow = " + firstRow); Integer resultsPerQuery = request.getRecordsCount(); log.debug("Integer resultsPerQuery = " + resultsPerQuery); Boolean isCount = request.getIsCount(); log.debug("boolean isCount = " + isCount.booleanValue()); getMaxRecordsPerQuery(); try { if (obj instanceof DetachedCriteria) { hCriteria = ((org.hibernate.criterion.DetachedCriteria) request.getRequest()) .getExecutableCriteria(session); log.info("Detached Criteria Query :" + hCriteria.toString()); callAuditAPIQuery(hCriteria.toString()); if (hCriteria != null) { if (isCount != null && isCount.booleanValue()) { rowCount = (Integer) hCriteria.setProjection(Projections.rowCount()).uniqueResult(); log.debug("DetachedCriteria ORMDAOImpl ===== count = " + rowCount); hCriteria.setResultTransformer(Criteria.ROOT_ENTITY); hCriteria.setProjection(null); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) hCriteria.setFirstResult(firstRow.intValue()); if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery; log.error(msg); throw new Exception(msg); } else { hCriteria.setMaxResults(resultsPerQuery.intValue()); } } else { hCriteria.setMaxResults(recordsPerQuery); }*/ // Set resultSet = new HashSet(hCriteria.list()); // rs = new ArrayList((Collection)resultSet); hCriteria.setMaxResults(maxRecordsPerQuery); rs = hCriteria.list(); } } } else if (obj instanceof NestedCriteria) { log.debug("ORMDAOImpl.query: it is a NestedCriteria Object ...."); System.out.println("Nested Criteria ~~~~~~~~~~~~~~~" + ((NestedCriteria) obj).getRoleName()); if (((NestedCriteria) obj).getRoleName() == null) { ((NestedCriteria) obj).setRoleName(""); } System.out.println("config: " + ormConn.getConfiguration(counter)); NestedCriteria2HQL converter = new NestedCriteria2HQL((NestedCriteria) obj, ormConn.getConfiguration(counter), session); query = converter.translate(); log.info("HQL Query :" + query.getQueryString()); callAuditAPIQuery(query.getQueryString()); if (query != null) { if (isCount != null && isCount.booleanValue()) { log.debug("ORMDAOImpl. isCount .... .... | converter.getCountQuery() = " + converter.getCountQuery().getQueryString()); rowCount = (Integer) converter.getCountQuery().uniqueResult(); log.debug("ORMDAOImpl HQL ===== count = " + rowCount); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { log.debug("Setting First Row to " + firstRow); query.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { log.debug("Setting Max Results to " + resultsPerQuery.intValue()); query.setMaxResults(resultsPerQuery.intValue()); } } else { log.debug("Setting Max Results to " + recordsPerQuery); query.setMaxResults(recordsPerQuery); }*/ query.setMaxResults(maxRecordsPerQuery); rs = query.list(); } } } else if (obj instanceof HQLCriteria) { Query hqlQuery = null; boolean isQueryFromGrid = isQueryFromGrid((HQLCriteria) obj); if (isQueryFromGrid) { hqlQuery = session.createQuery(modifiyQueryFromGrid(((HQLCriteria) obj).getHqlString())); } else { hqlQuery = session.createQuery(((HQLCriteria) obj).getHqlString()); } log.info("HQL Criteria Query :" + hqlQuery.getQueryString()); callAuditAPIQuery(hqlQuery.getQueryString()); if (isCount != null && isCount.booleanValue()) { rowCount = new Integer(hqlQuery.list().size()); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { hqlQuery.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { hqlQuery.setMaxResults(resultsPerQuery.intValue()); } } else { hqlQuery.setMaxResults(maxRecordsPerQuery); }*/ hqlQuery.setMaxResults(maxRecordsPerQuery); rs = hqlQuery.list(); if (isQueryFromGrid) { rs = createObjectList(ormConn.getConfiguration(counter).getClassMapping(entityName), entityName, rs); } } } else if (obj instanceof CQLQuery) { HibernateQueryWrapper queryWrapper = CQL2HQL.translate((CQLQuery) obj, false, request.getCaseSensitivity().booleanValue()); String hql = queryWrapper.getHql(); List params = queryWrapper.getParameters(); log.info("CQL Query :" + hql); callAuditAPIQuery(hql); Query hqlQuery = session.createQuery(hql); for (int i = 0; i < params.size(); i++) hqlQuery.setParameter(i, params.get(i)); if (isCount != null && isCount.booleanValue()) { rowCount = new Integer(hqlQuery.list().size()); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { hqlQuery.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { hqlQuery.setMaxResults(resultsPerQuery.intValue()); } } else { hqlQuery.setMaxResults(maxRecordsPerQuery); }*/ hqlQuery.setMaxResults(maxRecordsPerQuery); rs = hqlQuery.list(); } } } catch (JDBCException ex) { log.error("JDBC Exception in ORMDAOImpl ", ex); throw new DAOException("JDBC Exception in ORMDAOImpl ", ex); } catch (org.hibernate.HibernateException hbmEx) { log.error(hbmEx.getMessage()); throw new DAOException("Hibernate problem ", hbmEx); } catch (Exception e) { log.error("Exception ", e); throw new DAOException("Exception in the ORMDAOImpl ", e); } finally { try { session.clear(); session.close(); } catch (Exception eSession) { log.error("Could not close the session - " + eSession.getMessage()); throw new DAOException("Could not close the session " + eSession); } } Response rsp = new Response(); if (isCount != null && isCount.booleanValue()) rsp.setRowCount(rowCount); else rsp.setResponse(rs); return rsp; }
From source file:it.eng.qbe.statement.hibernate.HQL2SQLStatementRewriter.java
License:Mozilla Public License
public String rewrite(String query) { String sqlQuery = null;/*from ww w . jav a 2 s .c o m*/ logger.debug("rewrite: HQL query to convert: " + query); Query hibQuery = session.createQuery(query); SessionFactory sessionFactory = session.getSessionFactory(); SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory; ASTQueryTranslatorFactory astQueryTranslatorFactory = new ASTQueryTranslatorFactory(); QueryTranslator queryTranslator = null; Class[] parsTypes = null; Method createQueryTranslatorMethod = null; try { // Hibernate 3.0 parsTypes = new Class[3]; parsTypes[0] = String.class; parsTypes[1] = Map.class; parsTypes[2] = SessionFactoryImplementor.class; createQueryTranslatorMethod = astQueryTranslatorFactory.getClass().getMethod("createQueryTranslator", parsTypes); try { queryTranslator = (QueryTranslator) createQueryTranslatorMethod.invoke(astQueryTranslatorFactory, new Object[] { hibQuery.getQueryString(), Collections.EMPTY_MAP, sessionFactoryImplementor }); } catch (Throwable e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { parsTypes = new Class[4]; parsTypes[0] = String.class; parsTypes[1] = String.class; parsTypes[2] = Map.class; parsTypes[3] = SessionFactoryImplementor.class; try { createQueryTranslatorMethod = astQueryTranslatorFactory.getClass() .getMethod("createQueryTranslator", parsTypes); if (createQueryTranslatorMethod != null) { try { queryTranslator = (QueryTranslator) createQueryTranslatorMethod.invoke( astQueryTranslatorFactory, new Object[] { String.valueOf(System.currentTimeMillis()), hibQuery.getQueryString(), Collections.EMPTY_MAP, sessionFactoryImplementor }); } catch (Throwable t) { t.printStackTrace(); } } } catch (NoSuchMethodException ex) { e.printStackTrace(); } } queryTranslator.compile(new HashMap(), false); sqlQuery = queryTranslator.getSQLString(); logger.debug("rewrite: generated SQL query: " + sqlQuery); return sqlQuery; }