List of usage examples for org.apache.commons.collections.map ListOrderedMap orderedMapIterator
public OrderedMapIterator orderedMapIterator()
From source file:edu.cornell.mannlib.vedit.tags.OptionTag.java
public int doEndTag() throws JspException { try {//from w w w . jav a 2 s .c om JspWriter out = pageContext.getOut(); List optList = null; ListOrderedMap optGroups = null; try { optList = (List) getFormObject().getOptionLists().get(name); outputOptionsMarkup(optList, out); } catch (ClassCastException e) { // maybe it's a ListOrderedMap of optgroups optGroups = (ListOrderedMap) getFormObject().getOptionLists().get(name); OrderedMapIterator ogKey = optGroups.orderedMapIterator(); while (ogKey.hasNext()) { String optGroupName = (String) ogKey.next(); out.println("<optgroup label=\"" + StringEscapeUtils.escapeHtml(optGroupName) + "\">"); outputOptionsMarkup((List) optGroups.get(optGroupName), out); out.println("</optgroup>"); } } catch (NullPointerException npe) { System.out.println("OptionTag could not find option list for " + name); } } catch (Exception ex) { ex.printStackTrace(); throw new JspException(ex.getMessage()); } return SKIP_BODY; // EVAL_PAGE; did colnames only //EVAL_PAGE in connection pooled version; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.EntityRetryController.java
public void doPost(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) { return;//from w w w .jav a 2s .com } VitroRequest vreq = new VitroRequest(request); String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN; //create an EditProcessObject for this and put it in the session EditProcessObject epo = super.createEpo(request); epo.setBeanClass(Individual.class); epo.setImplementationClass(IndividualImpl.class); String action = null; if (epo.getAction() == null) { action = "insert"; epo.setAction("insert"); } else { action = epo.getAction(); } LoginStatusBean loginBean = LoginStatusBean.getBean(request); WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI()); IndividualDao ewDao = myWebappDaoFactory.getIndividualDao(); epo.setDataAccessObject(ewDao); VClassDao vcDao = myWebappDaoFactory.getVClassDao(); VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao(); DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao(); Individual individualForEditing = null; if (epo.getUseRecycledBean()) { individualForEditing = (Individual) epo.getNewBean(); } else { String uri = vreq.getParameter("uri"); if (uri != null) { try { individualForEditing = (Individual) ewDao.getIndividualByURI(uri); action = "update"; epo.setAction("update"); } catch (NullPointerException e) { log.error("Need to implement 'record not found' error message."); } } else { individualForEditing = new IndividualImpl(); if (vreq.getParameter("VClassURI") != null) { individualForEditing.setVClassURI(vreq.getParameter("VClassURI")); } } epo.setOriginalBean(individualForEditing); //make a simple mask for the entity's id Object[] simpleMaskPair = new Object[2]; simpleMaskPair[0] = "URI"; simpleMaskPair[1] = individualForEditing.getURI(); epo.getSimpleMask().add(simpleMaskPair); } //set any validators LinkedList lnList = new LinkedList(); lnList.add(new RequiredFieldValidator()); epo.getValidatorMap().put("Name", lnList); //make a postinsert pageforwarder that will send us to a new entity's fetch screen epo.setPostInsertPageForwarder(new EntityInsertPageForwarder()); epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl)); //set the getMethod so we can retrieve a new bean after we've inserted it try { Class[] args = new Class[1]; args[0] = String.class; epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args)); } catch (NoSuchMethodException e) { log.error("EntityRetryController could not find the entityByURI method in the dao"); } epo.setIdFieldName("URI"); epo.setIdFieldClass(String.class); HashMap hash = new HashMap(); if (individualForEditing.getVClassURI() == null) { // we need to do a special thing here to make an option list with option groups for the classgroups. List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals Iterator classGroupIt = classGroups.iterator(); ListOrderedMap optGroupMap = new ListOrderedMap(); while (classGroupIt.hasNext()) { VClassGroup group = (VClassGroup) classGroupIt.next(); List classes = group.getVitroClassList(); optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name", individualForEditing.getVClassURI(), null, false)); } hash.put("VClassURI", optGroupMap); } else { VClass vClass = null; Option opt = null; try { vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI()); } catch (Exception e) { } if (vClass != null) { opt = new Option(vClass.getURI(), vClass.getName(), true); } else { opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true); } List<Option> optList = new LinkedList<Option>(); optList.add(opt); hash.put("VClassURI", optList); } hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing)); hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing)); hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing)); FormObject foo = new FormObject(); foo.setOptionLists(hash); ListOrderedMap dpMap = new ListOrderedMap(); //make dynamic datatype property fields List<VClass> vclasses = individualForEditing.getVClasses(true); if (vclasses == null) { vclasses = new ArrayList<VClass>(); if (individualForEditing.getVClassURI() != null) { try { VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao() .getVClassByURI(individualForEditing.getVClassURI()); if (cls != null) { vclasses.add(cls); } } catch (Exception e) { } } } List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>(); for (VClass cls : vclasses) { List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI()); for (DataProperty dp : dataprops) { boolean notDuplicate = true; for (DataProperty existingDp : allApplicableDataprops) { if (existingDp.getURI().equals(dp.getURI())) { notDuplicate = false; break; } } if (notDuplicate) { allApplicableDataprops.add(dp); } } } Collections.sort(allApplicableDataprops); if (allApplicableDataprops != null) { Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator(); while (datapropsIt.hasNext()) { DataProperty d = datapropsIt.next(); if (!dpMap.containsKey(d.getURI())) { dpMap.put(d.getURI(), d); } } if (individualForEditing.getDataPropertyList() != null) { Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator(); while (existingDps.hasNext()) { DataProperty existingDp = existingDps.next(); // Since the edit form begins with a "name" field, which gets saved as the rdfs:label, // do not want to include the label as well. if (!existingDp.getPublicName().equals("label")) { dpMap.put(existingDp.getURI(), existingDp); } } } List<DynamicField> dynamicFields = new ArrayList(); Iterator<String> dpHashIt = dpMap.orderedMapIterator(); while (dpHashIt.hasNext()) { String uri = dpHashIt.next(); DataProperty dp = (DataProperty) dpMap.get(uri); DynamicField dynamo = new DynamicField(); dynamo.setName(dp.getPublicName()); dynamo.setTable("DataPropertyStatement"); dynamo.setVisible(dp.getDisplayLimit()); dynamo.setDeleteable(true); DynamicFieldRow rowTemplate = new DynamicFieldRow(); Map parameterMap = new HashMap(); parameterMap.put("DatatypePropertyURI", dp.getURI()); rowTemplate.setParameterMap(parameterMap); dynamo.setRowTemplate(rowTemplate); try { Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator(); while (existingValues.hasNext()) { DataPropertyStatement existingValue = existingValues.next(); DynamicFieldRow row = new DynamicFieldRow(); //TODO: UGH //row.setId(existingValue.getId()); row.setParameterMap(parameterMap); row.setValue(existingValue.getData()); if (dynamo.getRowList() == null) dynamo.setRowList(new ArrayList()); dynamo.getRowList().add(row); } } catch (NullPointerException npe) { //whatever } if (dynamo.getRowList() == null) dynamo.setRowList(new ArrayList()); dynamo.getRowList().add(rowTemplate); dynamicFields.add(dynamo); } foo.setDynamicFields(dynamicFields); } foo.setErrorMap(epo.getErrMsgMap()); epo.setFormObject(foo); // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd"); FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap()); List cList = new ArrayList(); cList.add(new IndividualDataPropertyStatementProcessor()); //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model epo.setChangeListenerList(cList); epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this ApplicationBean appBean = vreq.getAppBean(); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp"); request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp"); request.setAttribute("epoKey", epo.getKey()); request.setAttribute("title", "Individual Editing Form"); request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>"); request.setAttribute("scripts", "/js/edit/entityRetry.js"); // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\""); request.setAttribute("_action", action); request.setAttribute("unqualifiedClassName", "Individual"); setRequestAttributes(request, epo); try { rd.forward(request, response); } catch (Exception e) { log.error("EntityRetryController could not forward to view."); log.error(e.getMessage()); log.error(e.getStackTrace()); } }
From source file:edu.mayo.informatics.lexgrid.convert.directConversions.MetaThesaurusToSQL.java
/** * Adds qualification to concepts and associations in the LexGrid * repository./*from w ww.j av a 2 s . co m*/ * * @param aq * Qualification information from the UMLS source. * @param constructHCD * Indicates whether artificial context values should be * constructed if not provided in the UMLS information. * @param rela * The relationship attribute defined by UMLS (can be empty or * null). * @param totalCount * The total number of context links qualified previously. * @return The number of contextual links qualified in the repository for * the given UMLS info. * @throws SQLException */ protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount) throws SQLException { // If a context identifier was assigned, use it. // If a context identifier is not assigned and the option to construct // is enabled, // derive one based on the root concept code and path to root AUI // values. int contextLinks = 0; String hcd = aq.qualifierValue; if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot) && StringUtils.isNotBlank(aq.sourceConceptCode)) { MessageDigest md = getSHA1(); md.reset(); md.update(aq.pathToRoot.getBytes()); hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes())); } if (StringUtils.isBlank(hcd)) return 0; // Iterate through the path to root and determine the codes for // participating AUIs. We maintain a LRU cache of AUIs to codes to // assist. // If the associated code is not in the cache, find and cache it here. ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap(); // Break up the path to root into AUIs ... String[] auis = aq.pathToRoot.split("\\."); if (auis.length > 0) { // Check the cache for each. If not found, perform and cache the // AUI to code mapping. PreparedStatement getPTRCode = umlsConnection2_ .prepareStatement("SELECT CUI FROM MRCONSO WHERE AUI = ?"); try { String nextCode, nextAUI; for (int i = 0; i < auis.length; i++) { // Check for registered code in the cache. nextAUI = auis[i]; nextCode = (String) auiToCodeCache_.get(nextAUI); // If not cached, perform lookup ... if (nextCode == null) { getPTRCode.setString(1, nextAUI); ResultSet ptrCodes = getPTRCode.executeQuery(); int count = 0; try { while (ptrCodes.next()) { count++; nextCode = ptrCodes.getString(1); } } finally { ptrCodes.close(); } // If one to one mapping (probably should always be, but // doesn't // hurt to check), add to the cache for quick lookup // later... if (count == 1) auiToCodeCache_.put(nextAUI, nextCode); } // Was it resolved? if (nextCode != null) orderedPtrAUIToCode.put(nextAUI, nextCode); } } finally { getPTRCode.close(); } } // Ensure we have included the original AUI to code mapping from the // provided UMLS qualification info; inserted last as the root // of the path. orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode); // ///////////////////////////////////////////////////////////////////// // We have all the participating codes and AUIs. // Add context qualifiers to the text presentation of each concept // based on code/AUI pairs. // ///////////////////////////////////////////////////////////////////// for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) { omi.next(); String aui = (String) omi.getKey(); String code = (String) omi.getValue(); if (code != null) qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd); } // ///////////////////////////////////////////////////////////////////// // At this point we have taken care of all the concept qualifiers. // Now find and similarly tag each participating association link // between AUIs in the path to root chain. // ///////////////////////////////////////////////////////////////////// // Statements to find LexGrid association to concept mappings. // Check source to target (parent association as processed) // or target to source (child association as processed). // Honor the association specified in the MRHIER entry, if provided. // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype' // association name; account for that here. String assoc = mapRela(rela); // If a specific relation attribute (rela) was not provided, consider // all relevant // hierarchical associations (including UMLS standard or source-specific // names). String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\'' : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName)); // Create statements to navigate both directions (up & down the // contextual chain). PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ? AND ") .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND " + stc_.sourceEntityCodeOrId + " = ? AND ") .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); // Statement to update a multi-attributes key for an association // mapping. PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE " + stc_.codingSchemeNameOrId + " = ?") .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?") .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString()); // Locate and qualify each affected association link with the context ID // ... try { PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 }; for (int s = 0; s < stmts.length; s++) { PreparedStatement stmt = stmts[s]; for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) { String code = (String) orderedPtrAUIToCode.getValue(i); String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1); stmt.setString(1, code); stmt.setString(2, codePrev); stmt.setString(3, aq.codingSchemeName); ResultSet results = stmt.executeQuery(); try { // Iterate through all relevant association links ... while (results.next()) { String multiAttributesKey = results .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY); String targetConceptCode = results.getString(stc_.targetEntityCodeOrId); String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId); String association = results.getString(stc_.entityCodeOrAssociationId); // If there is no key to correlate to the // multi-attributes table, // construct and add now. if (multiAttributesKey == null) { StringBuffer key = new StringBuffer().append(System.currentTimeMillis()) .append((int) Math.floor((Math.random() * 100000))).append(totalCount); multiAttributesKey = key.substring(0, Math.min(50, key.length())); updateMAK.setString(1, multiAttributesKey); updateMAK.setString(2, aq.codingSchemeName); updateMAK.setString(3, sourceConceptCode); updateMAK.setString(4, targetConceptCode); updateMAK.setString(5, association); updateMAK.execute(); } // Add a context qualifier to the multi-attributes // table. try { addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName, multiAttributesKey, aq.qualifierName, hcd); contextLinks++; } catch (SQLException e) { // Because we qualify all relationships along // the PTR and // the HCD is identical for siblings at the same // PTR some // exceptions with regards to identical keys // will come up. // We try to bypass altogether if the message // indicates duplication. // However, message text can vary based on the // database engine. // Rather than exit in error, log the message // and continue. if (!e.getMessage().contains("Duplicate")) { messages_.warn("Unable to add context qualifier to association.", e); } } } } finally { results.close(); } } } } finally { updateMAK.close(); getRelationship_1.close(); getRelationship_2.close(); } return contextLinks; }
From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.UMLSBaseCode.java
/** * Adds qualification to concepts and associations in the LexGrid * repository./*from www .ja v a 2 s .c om*/ * * @param aq * Qualification information from the UMLS source. * @param constructHCD * Indicates whether artificial context values should be * constructed if not provided in the UMLS information. * @param rela * The relationship attribute defined by UMLS (can be empty or * null). * @param totalCount * The total number of context links qualified previously. * @return The number of contextual links qualified in the repository for * the given UMLS info. * @throws SQLException */ protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount) throws SQLException { // If a context identifier was assigned, use it. // If a context identifier is not assigned and the option to construct // is enabled, // derive one based on the root concept code and path to root AUI // values. int contextLinks = 0; String hcd = aq.qualifierValue; if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot) && StringUtils.isNotBlank(aq.sourceConceptCode)) { MessageDigest md = getSHA1(); md.reset(); md.update(aq.pathToRoot.getBytes()); hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes())); } if (StringUtils.isBlank(hcd)) return 0; // Iterate through the path to root and determine the codes for // participating AUIs. We maintain a LRU cache of AUIs to codes to // assist. // If the associated code is not in the cache, find and cache it here. ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap(); // Break up the path to root into AUIs ... String[] auis = aq.pathToRoot.split("\\."); if (auis.length > 0) { // Check the cache for each. If not found, perform and cache the // AUI to code mapping. PreparedStatement getPTRCode = umlsConnection2_ .prepareStatement("SELECT CODE FROM MRCONSO WHERE AUI = ?"); try { String nextCode, nextAUI; for (int i = 0; i < auis.length; i++) { // Check for registered code in the cache. nextAUI = auis[i]; nextCode = (String) auiToCodeCache_.get(nextAUI); // If not cached, perform lookup ... if (nextCode == null) { getPTRCode.setString(1, nextAUI); ResultSet ptrCodes = getPTRCode.executeQuery(); int count = 0; try { while (ptrCodes.next()) { count++; nextCode = ptrCodes.getString(1); } } finally { ptrCodes.close(); } // If one to one mapping (probably should always be, but // doesn't // hurt to check), add to the cache for quick lookup // later... if (count == 1) auiToCodeCache_.put(nextAUI, nextCode); } // Was it resolved? if (nextCode != null) orderedPtrAUIToCode.put(nextAUI, nextCode); } } finally { getPTRCode.close(); } } // Ensure we have included the original AUI to code mapping from the // provided UMLS qualification info; inserted last as the root // of the path. orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode); // ///////////////////////////////////////////////////////////////////// // We have all the participating codes and AUIs. // Add context qualifiers to the text presentation of each concept // based on code/AUI pairs. // ///////////////////////////////////////////////////////////////////// for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) { omi.next(); String aui = (String) omi.getKey(); String code = (String) omi.getValue(); if (code != null) qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd); } // ///////////////////////////////////////////////////////////////////// // At this point we have taken care of all the concept qualifiers. // Now find and similarly tag each participating association link // between AUIs in the path to root chain. // ///////////////////////////////////////////////////////////////////// // Statements to find LexGrid association to concept mappings. // Check source to target (parent association as processed) // or target to source (child association as processed). // Honor the association specified in the MRHIER entry, if provided. // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype' // association name; account for that here. String assoc = mapRela(rela); // If a specific relation attribute (rela) was not provided, consider // all relevant // hierarchical associations (including UMLS standard or source-specific // names). String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\'' : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName)); // Create statements to navigate both directions (up & down the // contextual chain). PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ? AND") .append(" " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer( "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", " + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND " + stc_.sourceEntityCodeOrId + " = ? AND") .append(" " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId + " IN (") .append(assocParam).append(")").toString()); // Statement to update a multi-attributes key for an association // mapping. PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ") .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY)) .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE " + stc_.codingSchemeNameOrId + " = ?") .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?") .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString()); // Locate and qualify each affected association link with the context ID // ... try { PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 }; for (int s = 0; s < stmts.length; s++) { PreparedStatement stmt = stmts[s]; for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) { String code = (String) orderedPtrAUIToCode.getValue(i); String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1); stmt.setString(1, code); stmt.setString(2, codePrev); stmt.setString(3, aq.codingSchemeName); ResultSet results = stmt.executeQuery(); try { // Iterate through all relevant association links ... while (results.next()) { String multiAttributesKey = results .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY); String targetConceptCode = results.getString(stc_.targetEntityCodeOrId); String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId); String association = results.getString(stc_.entityCodeOrAssociationId); // If there is no key to correlate to the // multi-attributes table, // construct and add now. if (multiAttributesKey == null) { StringBuffer key = new StringBuffer().append(System.currentTimeMillis()) .append((int) Math.floor((Math.random() * 100000))).append(totalCount); multiAttributesKey = key.substring(0, Math.min(50, key.length())); updateMAK.setString(1, multiAttributesKey); updateMAK.setString(2, aq.codingSchemeName); updateMAK.setString(3, sourceConceptCode); updateMAK.setString(4, targetConceptCode); updateMAK.setString(5, association); updateMAK.execute(); } // Add a context qualifier to the multi-attributes // table. try { addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName, multiAttributesKey, aq.qualifierName, hcd); contextLinks++; } catch (SQLException e) { // Because we qualify all relationships along // the PTR and // the HCD is identical for siblings at the same // PTR some // exceptions with regards to identical keys // will come up. // We try to bypass altogether if the message // indicates duplication. // However, message text can vary based on the // database engine. // Rather than exit in error, log the message // and continue. if (!e.getMessage().contains("Duplicate")) { messages_.warn("Unable to add context qualifier to association.", e); } } } } finally { results.close(); } } } } finally { updateMAK.close(); getRelationship_1.close(); getRelationship_2.close(); } return contextLinks; }