List of usage examples for java.lang String compareToIgnoreCase
public int compareToIgnoreCase(String str)
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version);//w ww .java 2s . c o m ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList(assocNames, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = -1;// NCImBrowserProperties.maxToReturn; boolean navigationForward = !direction; boolean navigationBackward = direction; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference(code, scheme), navigationForward, navigationBackward, 1, 1, new LocalNameList(), null, null, maxToReturn); String qualifier_name = null; String qualifier_value = null; if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); if (!direction) targetof = ref.getSourceOf(); if (targetof != null) { Association[] associations = targetof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { String associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt, assoc.getAssociationName()); if (associationName.compareToIgnoreCase("equivalentClass") != 0) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = "NA"; String asso_source = "NA"; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac.getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } for (NameAndValue qual : ac.getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("source") == 0) { asso_source = qualifier_value; // replace // associationName // by // Rela // value break; } } } v.add(associationName + "|" + asso_label + "|" + ac.getReferencedEntry().getEntityDescription().getContent() + "|" + ac.getReferencedEntry().getEntityCode() + "|" + asso_source); } } } } } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
public ResolvedConceptReferencesIteratorWrapper searchByProperties(Vector schemes, Vector versions, String matchText, String source, String matchAlgorithm, boolean excludeDesignation, boolean ranking, int maxToReturn) { if (matchAlgorithm == null || matchText == null) { return null; }/* www .j a v a2 s . co m*/ String matchText0 = matchText; String matchAlgorithm0 = matchAlgorithm; matchText0 = matchText0.trim(); _logger.debug("searchByProperties..." + matchText); //if (matchText == null || matchText.length() == 0) { if (matchText.length() == 0) { return null; } matchText = matchText.trim(); if (matchAlgorithm.compareToIgnoreCase("contains") == 0) { matchAlgorithm = findBestContainsAlgorithm(matchText); } CodedNodeSet cns = null; ResolvedConceptReferencesIterator iterator = null; String scheme = null; String version = null; try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } Vector cns_vec = new Vector(); for (int i = 0; i < schemes.size(); i++) { cns = null; iterator = null; scheme = (String) schemes.elementAt(i); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); version = (String) versions.elementAt(i); if (version != null) versionOrTag.setVersion(version); try { //cns = lbSvc.getNodeSet(scheme, versionOrTag, null); cns = getNodeSet(lbSvc, scheme, versionOrTag); if (cns != null) { try { LocalNameList propertyNames = new LocalNameList(); CodedNodeSet.PropertyType[] propertyTypes = getAllPropertyTypes(); if (excludeDesignation) { propertyTypes = getAllNonPresentationPropertyTypes(); } String language = null; try { cns = cns.restrictToMatchingProperties(propertyNames, propertyTypes, matchText, matchAlgorithm, language); } catch (Exception e) { _logger.error("\t(*) restrictToMatchingProperties throws exceptions???: " + matchText + " matchAlgorithm: " + matchAlgorithm); // e.printStackTrace(); } try { cns = restrictToSource(cns, source); } catch (Exception e) { _logger.error("\t(*) restrictToSource throws exceptions???: " + matchText + " matchAlgorithm: " + matchAlgorithm); // e.printStackTrace(); } } catch (Exception ex) { _logger.error("\t(*) searchByProperties2 throws exceptions."); // ex.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); // return null; } if (cns != null) { cns_vec.add(cns); } } iterator = null; /* * cns = union(cns_vec); if (cns == null) return null; */ LocalNameList restrictToProperties = null;// new LocalNameList(); boolean resolveConcepts = false; SortOptionList sortCriteria = null; if (ranking) { sortCriteria = Constructors.createSortOptionList(new String[] { "matchToQuery" }); } else { sortCriteria = Constructors.createSortOptionList(new String[] { "entityDescription" }); // code _logger.debug("*** Sort alphabetically..."); resolveConcepts = false; } try { try { long ms = System.currentTimeMillis(), delay = 0; // iterator = cns.resolve(sortCriteria, null, // restrictToProperties, null, resolveConcepts); iterator = new QuickUnionIterator(cns_vec, sortCriteria, null, restrictToProperties, null, resolveConcepts); } catch (Exception e) { _logger.error("Method: SearchUtil.searchByProperties"); _logger.error("* ERROR: cns.resolve throws exceptions."); _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } if (!excludeDesignation) { int lcv = 0; int iterator_size = 0; if (iterator != null) { try { iterator_size = iterator.numberRemaining(); } catch (Exception ex) { } } while (iterator_size == 0 && lcv < schemes.size()) { scheme = (String) schemes.elementAt(lcv); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); version = (String) versions.elementAt(lcv); if (version != null) versionOrTag.setVersion(version); iterator = matchConceptCode(scheme, version, matchText0, source, CODE_SEARCH_ALGORITHM); if (iterator != null) { try { iterator_size = iterator.numberRemaining(); } catch (Exception ex) { } } lcv++; } } // return iterator; return new ResolvedConceptReferencesIteratorWrapper(iterator); }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
public ResolvedConceptReferencesIteratorWrapper searchByNameOrCode(Vector<String> schemes, Vector<String> versions, String matchText, String source, String matchAlgorithm, boolean ranking, int maxToReturn, String searchTarget) { if (searchTarget == null) searchTarget = SEARCH_BY_NAME_ONLY; try {//w ww .jav a2s . c o m if (matchText == null || matchText.trim().length() == 0) return null; Utils.StopWatch stopWatch = new Utils.StopWatch(); Utils.StopWatch stopWatchTotal = new Utils.StopWatch(); boolean debug_flag = false; matchText = matchText.trim(); _logger.debug("searchByName ... " + matchText); // p11.1-q11.1 // /100{WBC} if (matchAlgorithm.compareToIgnoreCase("contains") == 0) { matchAlgorithm = findBestContainsAlgorithm(matchText); } LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); Vector<CodedNodeSet> cns_vec = new Vector<CodedNodeSet>(); for (int i = 0; i < schemes.size(); i++) { stopWatch.start(); String scheme = (String) schemes.elementAt(i); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); String version = (String) versions.elementAt(i); if (version != null) { versionOrTag.setVersion(version); } //Name search if (searchTarget.compareToIgnoreCase(SEARCH_BY_CODE_ONLY) != 0) { CodedNodeSet cns = getNodeSet(lbSvc, scheme, versionOrTag); if (cns != null) { cns = cns.restrictToMatchingDesignations(matchText, null, matchAlgorithm, null); cns = restrictToSource(cns, source); } if (cns != null) { cns_vec.add(cns); } } else { CodedNodeSet.PropertyType[] propertyTypes = null; LocalNameList sourceList = null; LocalNameList contextList = null; NameAndValueList qualifierList = null; String code = matchText; CodedNodeSet cns_code = getCodedNodeSetContrainingCode(lbSvc, scheme, versionOrTag, code); if (cns_code != null && includeInQuickUnion(cns_code)) { cns_vec.add(cns_code); } // source code match: CodedNodeSet cns_src_code = null; if (DataUtils.hasSourceCodeQualifier(scheme)) { String sourceAbbr = source; qualifierList = null; if (code != null && code.compareTo("") != 0) { qualifierList = new NameAndValueList(); NameAndValue nv = new NameAndValue(); nv.setName("source-code"); nv.setContent(code); qualifierList.addNameAndValue(nv); } LocalNameList propertyLnL = null; // sourceLnL Vector<String> w2 = new Vector<String>(); LocalNameList sourceLnL = null; if (sourceAbbr != null && (sourceAbbr.compareTo("*") == 0 || sourceAbbr.compareToIgnoreCase("ALL") == 0)) { sourceLnL = null; } else if (sourceAbbr != null) { w2.add(sourceAbbr); sourceLnL = vector2LocalNameList(w2); } SortOptionList sortCriteria = null;// Constructors.createSortOptionList(new // String[]{"matchToQuery", "code"}); contextList = null; try { cns_src_code = getNodeSet(lbSvc, scheme, versionOrTag); CodedNodeSet.PropertyType[] types = new PropertyType[] { PropertyType.PRESENTATION }; cns_src_code = cns_src_code.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList); } catch (Exception ex) { ex.printStackTrace(); } } if (cns_src_code != null) cns_vec.add(cns_src_code); } } if (debug_flag) _logger.debug("searchByNameAndCode QuickUnion delay (msec): " + stopWatch.duration()); SortOptionList sortCriteria = null; LocalNameList restrictToProperties = new LocalNameList(); boolean resolveConcepts = false; if (ranking) { sortCriteria = null;// Constructors.createSortOptionList(new // String[]{"matchToQuery"}); } else { sortCriteria = Constructors.createSortOptionList(new String[] { "entityDescription" }); // code _logger.debug("*** Sort alphabetically..."); } stopWatch.start(); if (debug_flag) _logger.debug("Calling cns.resolve to resolve the union CNS ... "); ResolvedConceptReferencesIterator iterator = new QuickUnionIterator(cns_vec, sortCriteria, null, restrictToProperties, null, resolveConcepts); if (debug_flag) _logger.debug("Resolve CNS union delay (msec): " + stopWatch.duration()); _logger.debug("Total search delay (msec): " + stopWatchTotal.duration()); return new ResolvedConceptReferencesIteratorWrapper(iterator); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java
/** * Get the submissions to the assessment made by all users. * //from w ww .j ava2 s . c o m * @param assessment * The assessment. * @param sort * The sort. * @param question * An optional question, to use for sort-by-score (the score would be for this question in the submission, not the overall). * @param filterByPermission * if true, return submissions only from users who are currently permitted to submit, otherwise return any submissions found. * @return A List<Submission> of the submissions for the assessment. */ protected List<SubmissionImpl> getAssessmentSubmissions(Assessment assessment, final FindAssessmentSubmissionsSort sort, final Question question, boolean filterByPermission) { // collect the submissions to this assessment List<SubmissionImpl> rv = this.storage.getAssessmentSubmissions(assessment); // get all possible users who can submit Set<String> userIds = this.securityService.getUsersIsAllowed(MnemeService.SUBMIT_PERMISSION, assessment.getContext()); // filter out any userIds that are not currently defined List<User> users = this.userDirectoryService.getUsers(userIds); userIds.clear(); for (User user : users) { userIds.add(user.getId()); } // if any user is not represented in the submissions we found, add an empty submission for (String userId : userIds) { boolean found = false; for (Submission s : rv) { if (s.getUserId().equals(userId)) { found = true; break; } } if (!found) { SubmissionImpl s = this.getPhantomSubmission(userId, assessment); rv.add(s); } } // filter out any submissions found that are not for one of the users in the userIds list (they may have lost permission) if (filterByPermission) { for (Iterator<SubmissionImpl> i = rv.iterator(); i.hasNext();) { SubmissionImpl submission = i.next(); if (!userIds.contains(submission.getUserId())) { i.remove(); } } } // for all but user name & status sorts, separate out the completed, not-started, in-progress List<SubmissionImpl> inProgress = new ArrayList<SubmissionImpl>(); List<SubmissionImpl> notStarted = new ArrayList<SubmissionImpl>(); if ((sort != FindAssessmentSubmissionsSort.userName_a) && (sort != FindAssessmentSubmissionsSort.userName_d) && (sort != FindAssessmentSubmissionsSort.status_a) && (sort != FindAssessmentSubmissionsSort.status_d)) { for (Iterator i = rv.iterator(); i.hasNext();) { SubmissionImpl submission = (SubmissionImpl) i.next(); if (!submission.getIsStarted().booleanValue()) { notStarted.add(submission); i.remove(); } else if (!submission.getIsComplete().booleanValue()) { inProgress.add(submission); i.remove(); } } } // sort - secondary sort of user name, or if primary is title, on submit date Collections.sort(rv, new Comparator() { public int compare(Object arg0, Object arg1) { int rv = 0; FindAssessmentSubmissionsSort secondary = null; switch (sort) { case userName_a: case userName_d: case status_a: case status_d: { String id0 = ((Submission) arg0).getUserId(); try { User u = userDirectoryService.getUser(id0); id0 = u.getSortName(); } catch (UserNotDefinedException e) { } String id1 = ((Submission) arg1).getUserId(); try { User u = userDirectoryService.getUser(id1); id1 = u.getSortName(); } catch (UserNotDefinedException e) { } rv = id0.compareToIgnoreCase(id1); // Note: leave status sort ascending if (sort == FindAssessmentSubmissionsSort.userName_d) rv = -1 * rv; secondary = FindAssessmentSubmissionsSort.sdate_a; break; } case final_a: case final_d: { Float final0 = null; Float final1 = null; if (question != null) { Answer a0 = ((Submission) arg0).getAnswer(question); Answer a1 = ((Submission) arg1).getAnswer(question); final0 = ((a0 == null) ? Float.valueOf(0f) : a0.getTotalScore()); final1 = ((a1 == null) ? Float.valueOf(0f) : a1.getTotalScore()); } else { final0 = ((Submission) arg0).getTotalScore(); final1 = ((Submission) arg1).getTotalScore(); } // null sorts small if ((final0 == null) && (final1 == null)) { rv = 0; } else if (final0 == null) { rv = -1; } else if (final1 == null) { rv = 1; } else { rv = final0.compareTo(final1); } if (sort == FindAssessmentSubmissionsSort.final_d) rv = -1 * rv; secondary = FindAssessmentSubmissionsSort.userName_a; break; } case sdate_a: case sdate_d: { Date date0 = ((Submission) arg0).getSubmittedDate(); Date date1 = ((Submission) arg1).getSubmittedDate(); if ((date0 == null) && (date1 == null)) { rv = 0; } else if (date0 == null) { rv = -1; } else if (date1 == null) { rv = 1; } else { rv = date0.compareTo(date1); } if (sort == FindAssessmentSubmissionsSort.sdate_d) rv = -1 * rv; secondary = FindAssessmentSubmissionsSort.userName_a; break; } case evaluated_a: case evaluated_d: { Boolean evaluated0 = ((Submission) arg0).getEvaluation().getEvaluated(); Boolean evaluated1 = ((Submission) arg1).getEvaluation().getEvaluated(); rv = evaluated0.compareTo(evaluated1); if (sort == FindAssessmentSubmissionsSort.evaluated_d) rv = -1 * rv; secondary = FindAssessmentSubmissionsSort.userName_a; break; } case released_a: case released_d: { Boolean released0 = ((Submission) arg0).getIsReleased(); Boolean released1 = ((Submission) arg1).getIsReleased(); rv = released0.compareTo(released1); if (sort == FindAssessmentSubmissionsSort.released_d) rv = -1 * rv; secondary = FindAssessmentSubmissionsSort.userName_a; break; } } // secondary sort FindAssessmentSubmissionsSort third = null; if ((rv == 0) && (secondary != null)) { switch (secondary) { case userName_a: { String id0 = ((Submission) arg0).getUserId(); try { User u = userDirectoryService.getUser(id0); id0 = u.getSortName(); } catch (UserNotDefinedException e) { } String id1 = ((Submission) arg1).getUserId(); try { User u = userDirectoryService.getUser(id1); id1 = u.getSortName(); } catch (UserNotDefinedException e) { } rv = id0.compareToIgnoreCase(id1); third = FindAssessmentSubmissionsSort.sdate_a; break; } case sdate_a: { Date date0 = ((Submission) arg0).getSubmittedDate(); Date date1 = ((Submission) arg1).getSubmittedDate(); if ((date0 == null) && (date1 == null)) { rv = 0; } else if (date0 == null) { rv = -1; } else if (date1 == null) { rv = 1; } else { rv = ((Submission) arg0).getSubmittedDate() .compareTo(((Submission) arg1).getSubmittedDate()); } break; } } } // third sort if ((rv == 0) && (third != null)) { switch (third) { case sdate_a: { Date date0 = ((Submission) arg0).getSubmittedDate(); Date date1 = ((Submission) arg1).getSubmittedDate(); if ((date0 == null) && (date1 == null)) { rv = 0; } else if (date0 == null) { rv = -1; } else if (date1 == null) { rv = 1; } else { rv = ((Submission) arg0).getSubmittedDate() .compareTo(((Submission) arg1).getSubmittedDate()); } break; } } } return rv; } }); // if we have in-progress and not-started to deal with if (!inProgress.isEmpty()) { // sort them by user name asc Collections.sort(inProgress, new Comparator() { public int compare(Object arg0, Object arg1) { int rv = 0; String id0 = ((Submission) arg0).getUserId(); try { User u = userDirectoryService.getUser(id0); id0 = u.getSortName(); } catch (UserNotDefinedException e) { } String id1 = ((Submission) arg1).getUserId(); try { User u = userDirectoryService.getUser(id1); id1 = u.getSortName(); } catch (UserNotDefinedException e) { } rv = id0.compareToIgnoreCase(id1); return rv; } }); rv.addAll(inProgress); } if (!notStarted.isEmpty()) { // sort them by user name asc Collections.sort(notStarted, new Comparator() { public int compare(Object arg0, Object arg1) { int rv = 0; String id0 = ((Submission) arg0).getUserId(); try { User u = userDirectoryService.getUser(id0); id0 = u.getSortName(); } catch (UserNotDefinedException e) { } String id1 = ((Submission) arg1).getUserId(); try { User u = userDirectoryService.getUser(id1); id1 = u.getSortName(); } catch (UserNotDefinedException e) { } rv = id0.compareToIgnoreCase(id1); return rv; } }); rv.addAll(notStarted); } return rv; }
From source file:org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean.java
public String cleanRadioButton() { // We get the id of the question String radioId = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap() .get("radioId"); StringBuffer redrawAnchorName = new StringBuffer("p"); String tmpAnchorName = ""; ArrayList parts = this.pageContents.getPartsContents(); for (int i = 0; i < parts.size(); i++) { SectionContentsBean sectionContentsBean = (SectionContentsBean) parts.get(i); String partSeq = sectionContentsBean.getNumber(); ArrayList items = sectionContentsBean.getItemContents(); for (int j = 0; j < items.size(); j++) { ItemContentsBean item = (ItemContentsBean) items.get(j); //Just delete the checkbox of the current question if (!item.getItemData().getItemId().toString().equals(radioId)) continue; String itemSeq = item.getItemData().getSequence().toString(); redrawAnchorName.append(partSeq); redrawAnchorName.append("q"); redrawAnchorName.append(itemSeq); if (tmpAnchorName.equals("") || tmpAnchorName.compareToIgnoreCase(redrawAnchorName.toString()) > 0) { tmpAnchorName = redrawAnchorName.toString(); }//from ww w.j a v a2s . c o m if (item.getItemData().getTypeId().longValue() == TypeIfc.MULTIPLE_CHOICE.longValue() || item.getItemData().getTypeId().longValue() == TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION .longValue() || item.getItemData().getTypeId().longValue() == TypeIfc.MULTIPLE_CHOICE_SURVEY.longValue() || item.getItemData().getTypeId().longValue() == TypeIfc.MATRIX_CHOICES_SURVEY .longValue()) { item.setUnanswered(true); if (item.getItemData().getTypeId().longValue() == TypeIfc.MATRIX_CHOICES_SURVEY.longValue()) { for (int k = 0; k < item.getMatrixArray().size(); k++) { MatrixSurveyBean selection = (MatrixSurveyBean) item.getMatrixArray().get(k); selection.setResponseFromCleanRadioButton(); } } else { for (int k = 0; k < item.getSelectionArray().size(); k++) { SelectionBean selection = (SelectionBean) item.getSelectionArray().get(k); //selection.setResponse(false); selection.setResponseFromCleanRadioButton(); } } ArrayList itemGradingData = new ArrayList(); Iterator iter = item.getItemGradingDataArray().iterator(); while (iter.hasNext()) { ItemGradingData itemgrading = (ItemGradingData) iter.next(); if (itemgrading.getItemGradingId() != null && itemgrading.getItemGradingId().intValue() > 0) { itemGradingData.add(itemgrading); itemgrading.setPublishedAnswerId(null); } } item.setItemGradingDataArray(itemGradingData); } if (item.getItemData().getTypeId().longValue() == TypeIfc.TRUE_FALSE.longValue()) { item.setResponseId(null); Iterator iter = item.getItemGradingDataArray().iterator(); if (iter.hasNext()) { ItemGradingData data = (ItemGradingData) iter.next(); data.setPublishedAnswerId(null); } } item.setReview(false); item.setRationale(""); } } syncTimeElapsedWithServer(); // Set the anchor setRedrawAnchorName(tmpAnchorName.toString()); return "takeAssessment"; }
From source file:gov.nih.nci.evs.browser.utils.DataUtils.java
public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try {//ww w .ja v a2 s. com LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) return null; LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); /* if (lbSvc == null) { Debug.println("lbSvc == null???"); return hmap; } */ CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors.createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList( Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches != null) { java.lang.Boolean incomplete = matches.getIncomplete(); // _logger.debug("(*) Number of matches: " + // matches.getResolvedConceptReferenceCount()); // _logger.debug("(*) Incomplete? " + incomplete); hmap.put(INCOMPLETE, incomplete.toString()); } else { return null; } if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; String directionalLabel = associationName; boolean navigatedFwd = true; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); } catch (Exception e) { Debug.println("(*) getDirectionalLabel throws exceptions: " + directionalLabel); } //Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac.getAssociationQualifiers().getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) { String directionalLabel = associationName; boolean navigatedFwd = false; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); // Debug.println("(**) directionalLabel: associationName " // + associationName + // " directionalLabel: " + // directionalLabel); } catch (Exception e) { Debug.println( "(**) getDirectionalLabel throws exceptions: " + directionalLabel); } //Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac.getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("rela") == 0) { // associationName = // qualifier_value; // // replace associationName // by Rela value asso_label = qualifier_value; break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } } } } } catch (Exception ex) { ex.printStackTrace(); } return hmap; }
From source file:net.cbtltd.rest.AbstractReservation.java
protected static synchronized ReservationResponse createReservationPayment(String pos, String productId, String fromDate, String toDate, String emailAddress, String familyName, String firstName, String notes, String cardNumber, String cardExpiryMonth, String cardExpiryYear, String amount, String currency, String phoneNumber, Integer cardType, Integer cvc, Integer adult, Integer child, String address, String country, String state, String city, String zip, Integer birthDay, Integer birthMonth, Integer birthYear, String altId) { resetValue(address);/* w w w. jav a 2s.c o m*/ resetValue(country); resetValue(city); resetValue(state); SqlSession sqlSession = RazorServer.openSession(); ReservationResponse response = new ReservationResponse(); PaymentTransaction paymentTransaction = null; PendingTransaction pendingTransaction = null; Reservation reservation = new Reservation(); boolean reservationFinished = false; GatewayHandler handler = null; try { if (StringUtils.isEmpty(pos) || StringUtils.isEmpty(productId) || StringUtils.isEmpty(fromDate) || StringUtils.isEmpty(toDate) || StringUtils.isEmpty(emailAddress) || StringUtils.isEmpty(familyName) | StringUtils.isEmpty(firstName) || StringUtils.isEmpty(phoneNumber) || cardType == null || child == null || StringUtils.isEmpty(currency) || birthDay == null || birthMonth == null || birthYear == null || amount == null || zip == null) { throw new ServiceException(Error.parameter_absent); } if (adult == null || adult < 1) { throw new ServiceException(Error.missing_adult_parameter); } if (StringUtils.isEmpty(cardNumber) || StringUtils.isEmpty(cardExpiryMonth) || StringUtils.isEmpty(cardExpiryYear) || cvc == null) { // throw new ServiceException(Error.credit_card_error); } //yyyy-mm-dd if (fromDate.compareToIgnoreCase(toDate) > 0) { throw new ServiceException(Error.date_range); } Date birthDate = null; if (birthYear != null && birthMonth != null && birthDay != null) { birthDate = stringToDate(birthYear, birthMonth - 1, birthDay); } boolean encodable = false; if (state != null) { encodable = CommonUtils .iso88591Encodable(new String[] { firstName, familyName, address, country, city, state }); } else { encodable = CommonUtils .iso88591Encodable(new String[] { firstName, familyName, address, country, city }); } if (!encodable) { throw new ServiceException(Error.parameter_invalid); } // String[] ignoreIds = {"179805", "90640", "179769","179791","179792","179793","179795","179801","179802", "179896", "179797", // "179799", "179800", "179803", "179804"}; // Credit card initialization CreditCard creditCard = new CreditCard(); creditCard.setFirstName(firstName); creditCard.setLastName(familyName); creditCard.setMonth(cardExpiryMonth); cardNumber = cardNumber.trim(); creditCard.setNumber(cardNumber); creditCard.setType(CreditCardType.get(cardType)); creditCard.setYear(cardExpiryYear); creditCard.setSecurityCode(cvc.toString()); // Initialization of necessary instances Product product = sqlSession.getMapper(ProductMapper.class).read(productId); if (!product.getState().equals(Product.CREATED)) { throw new ServiceException(Error.product_inactive); } int supplierId = Integer.valueOf(product.getSupplierid()); PropertyManagerInfo propertyManagerInfo = sqlSession.getMapper(PropertyManagerInfoMapper.class) .readbypmid(supplierId); if (propertyManagerInfo == null) { throw new ServiceException(Error.database_cannot_find_property_manager, String.valueOf(supplierId)); } response.setPropertyName(product.getName()); response.setPropertyAddress(ReservationService.getPropertyLocation(sqlSession, product)); // Initialization end Party channelPartnerParty = JSONService.getParty(sqlSession, pos); // Party channelPartnerParty = JSONService.getPartyWithPMCheck(sqlSession, pos, product.getSupplierid()); // this method checks agent's status and throws an exception in case of agent is inactive if (channelPartnerParty == null) { throw new ServiceException(Error.reservation_agentid); } // Party customer = JSONService.getCustomer(sqlSession, emailAddress, familyName, firstName, product.getSupplierid(), phoneNumber, channelPartnerParty); Party customer = processCustomer(sqlSession, emailAddress, familyName, firstName, product, phoneNumber, channelPartnerParty, product.getSupplierid(), channelPartnerParty, address, country, city, zip, state, birthDate); Party propertyManager = sqlSession.getMapper(PartyMapper.class) .read(propertyManagerInfo.getPropertyManagerId().toString()); response.setPropertyManagerName(propertyManager.getName()); response.setPropertyManagerEmail(propertyManager.getEmailaddress()); response.setPropertyManagerPhone(propertyManager.getDayphone()); // Reservation processing reservation = PaymentHelper.prepareReservation(channelPartnerParty, customer, product, propertyManagerInfo, fromDate, toDate, notes, productId, adult, child); // END INITIALIZATION BLOCK Double amountToCheck = PaymentHelper.roundAmountTwoDecimals(amount); Double amountDifference = PaymentHelper.amountDifference(sqlSession, reservation, amountToCheck, currency); if (amountDifference > 1 && (BPThreadLocal.get() == null || !BPThreadLocal.get())) { throw new ServiceException(Error.price_not_match, "passed: " + amountToCheck + currency + ", difference: " + amountDifference); } if (propertyManagerInfo.getFundsHolder() == ManagerToGateway.bookingnet_HOLDER) { // amount = PaymentHelper.convertToDefaultMbpCurrency(sqlSession, reservation, propertyManagerInfo, PaymentHelper.roundAmountTwoDecimals(amount), currency).toString(); currency = PaymentHelper.DEFAULT_bookingnet_CURRENCY; } else { // amount = PaymentService.convertCurrency(sqlSession, currency, reservation.getCurrency(), PaymentHelper.roundAmountTwoDecimals(amount)).toString(); currency = product.getCurrency(); } if (reservation.getAltpartyid() == null || !Arrays.asList(livePricingIds).contains(reservation.getAltpartyid())) { ReservationService.computePrice(sqlSession, reservation, currency); Double deposit = ReservationService.getDeposit(reservation, propertyManagerInfo); reservation.setDeposit(deposit); reservation.setCost( reservation.getQuote() * ReservationService.getDiscountfactor(sqlSession, reservation)); } else { LOG.error("PartnerService.readPrice started"); PartnerService.readPrice(sqlSession, reservation, product.getAltid(), currency); if ((reservation.getPrice() == null || reservation.getPrice() <= 0) || (reservation.getQuote() == null || reservation.getQuote() <= 0)) { throw new ServiceException(Error.price_missing, "Price was resturned null or 0"); } ReservationService.computeLivePrice(sqlSession, reservation, null, currency); LOG.error("PartnerService.readPrice finished"); } if (reservation.getPrice() == 0.0) { throw new ServiceException(Error.price_data); } // END PRICE BLOCK boolean available = sqlSession.getMapper(ReservationMapper.class).available(reservation); if (!available) { throw new ServiceException(Error.product_not_available); } reservation.setState(Reservation.State.Provisional.name()); reservation .setName(SessionService.pop(sqlSession, reservation.getOrganizationid(), Serial.RESERVATION)); reservation.setCollisions(ReservationService.getCollisions(sqlSession, reservation)); if (reservation.hasCollisions()) { throw new ServiceException(Error.product_not_available, reservation.getProductFromToDate()); } if (StringUtils.isNotEmpty(altId)) { reservation.setAltid(altId); } sqlSession.getMapper(ReservationMapper.class).create(reservation); ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard); // END AVAILABILITY BLOCK ManagerToGateway managerToGateway = null; PaymentGatewayProvider paymentGatewayProvider = null; Map<String, String> resultMap = null; int paymentGatewayId = -1; // Processing charge type String chargeType = PaymentHelper.getChargeType(propertyManagerInfo, reservation); Double firstPayment = PaymentHelper.getFirstPayment(reservation, propertyManagerInfo); Double secondPayment = PaymentHelper.getSecondPayment(reservation, propertyManagerInfo); response.setDownPayment(firstPayment); Double amountToCharge = PaymentHelper.isFullPaymentMethod(chargeType) ? firstPayment + secondPayment : firstPayment; if (PaymentHelper.isApiPaymentMethod(chargeType)) { if (StringUtils.isEmpty(reservation.getState())) { reservation.setState(Reservation.State.Confirmed.name()); } resultMap = PartnerService.createReservationAndPayment(sqlSession, reservation, creditCard); if (resultMap != null && PaymentHelper.isDepositPaymentMethod(chargeType) && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) { pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName, firstName, cardNumber, phoneNumber, reservation, product, propertyManagerInfo.getPropertyManagerId(), propertyManagerInfo, secondPayment, null, resultMap, null); sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction); sqlSession.commit(); } } else if (chargeType.equalsIgnoreCase(PaymentHelper.FULL_PAYMENT_METHOD) || chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD)) { /* * The following line is bad because this is the final payment. Once it was charged, we have no information about renter's CC * and in case of cancellation (deposit and full payment) or second payment (deposit payment) we have no CC information about renter. * Thus, there is always needed to create the payment profile in payment gateway and store returned information to database. * * resultMap = handler.createPaymentByCreditCard(product.getCurrency(), firstPayment); */ // Payment gateway initialization managerToGateway = sqlSession.getMapper(ManagerToGatewayMapper.class).readBySupplierId(supplierId); paymentGatewayId = managerToGateway.getPaymentGatewayId(); paymentGatewayProvider = PaymentGatewayHolder.getPaymentGateway(paymentGatewayId); handler = PaymentHelper.initializeHandler(propertyManagerInfo, managerToGateway, creditCard); if (!paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) { resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge, reservation, handler, currency, creditCard, paymentGatewayId); } // Pending transaction processing if (resultMap != null && chargeType.equalsIgnoreCase(PaymentHelper.DEPOSIT_PAYMENT_METHOD) && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) { pendingTransaction = PaymentHelper.preparePendingTransaction(sqlSession, pos, familyName, firstName, cardNumber, phoneNumber, reservation, product, supplierId, propertyManagerInfo, secondPayment, paymentGatewayProvider, resultMap, paymentGatewayId); sqlSession.getMapper(PendingTransactionMapper.class).create(pendingTransaction); } } else if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) { setReservationState(reservation, chargeType); response.setReservationInfo(new ReservationInfo(reservation)); sqlSession.getMapper(ReservationMapper.class).update(reservation); sqlSession.commit(); } else { throw new ServiceException(Error.payment_method_unsupported); } if (propertyManagerInfo.getPropertyManagerId() != Integer.valueOf(RazorConfig.getNextpaxNovasolId())) { paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation, propertyManagerInfo, firstPayment, managerToGateway, cardNumber, Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false); } if (chargeType.equalsIgnoreCase(PaymentHelper.MAIL_PAYMENT_METHOD)) { sendEmails(sqlSession, paymentTransaction, chargeType); return response; } // END PAYMENT BLOCK if (resultMap != null && resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED) || (paymentGatewayProvider != null && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS))) { if (product.hasAltpartyid() && !PaymentHelper.isApiPaymentMethod(chargeType)) { if (reservation.getState() == null) { reservation.setState(Reservation.State.Confirmed.name()); } try { PartnerService.createReservation(sqlSession, reservation); } catch (ServiceException e) { LOG.error(e.getMessage()); } } MonitorService.update(sqlSession, Data.Origin.JQUERY, NameId.Type.Reservation, reservation); if (paymentGatewayProvider != null && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) { if (paymentGatewayId != -1 && paymentGatewayProvider != null && (!reservation.getState().equals(Reservation.State.Cancelled.name()))) { resultMap = PaymentHelper.processPayment(sqlSession, paymentGatewayProvider, amountToCharge, reservation, handler, currency, creditCard, paymentGatewayId); paymentTransaction = PaymentHelper.preparePaymentTransaction(sqlSession, reservation, propertyManagerInfo, firstPayment, managerToGateway, cardNumber, Integer.valueOf(channelPartnerParty.getId()), product, resultMap, false); if (resultMap == null || !resultMap.get(GatewayHandler.STATE).equals(GatewayHandler.ACCEPTED)) { LOG.error("An error occurred while processing your payment"); PartnerService.cancelReservation(sqlSession, reservation); reservation.setState(Reservation.State.Cancelled.name()); if (resultMap != null) { response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG)); } else { response.setErrorMessage("Something went wrong with payment processing"); } } else { PartnerService.confirmReservation(sqlSession, reservation); } } } // END PARTNER RESERVATION BLOCK // refund transaction made in case of PMS rejected the reservation if (paymentTransaction != null && reservation.getState() != null && reservation.getState().equals(Reservation.State.Cancelled.name())) { List<PaymentTransaction> paymentTransactions = new ArrayList<PaymentTransaction>(); paymentTransactions.add(paymentTransaction); refundAmount(sqlSession, supplierId, paymentTransactions, firstPayment); cancelPendingTransactions(sqlSession, reservation); reservationFinished = true; throw new ServiceException(Error.pms_reservation_reject); } else if (paymentTransaction == null && paymentGatewayProvider != null && paymentGatewayProvider.getName().equals(PaymentGatewayHolder.DIBS)) { cancelPendingTransactions(sqlSession, reservation); reservationFinished = true; throw new ServiceException(Error.pms_reservation_reject); } else { setReservationState(reservation, chargeType); reservationFinished = true; } ReservationService.createEvent(sqlSession, paymentTransaction, reservation, creditCard); sqlSession.getMapper(ReservationMapper.class).update(reservation); // Pending transaction end sendEmails(sqlSession, paymentTransaction, chargeType); // END VERIFICATION BLOCK } else { reservation.setState(Reservation.State.Cancelled.name()); sqlSession.getMapper(ReservationMapper.class).update(reservation); if (resultMap != null && resultMap.get(GatewayHandler.ERROR_MSG) != null) { LOG.error("An error occurred while processing your payment"); response.setErrorMessage(resultMap.get(GatewayHandler.ERROR_MSG)); } else { LOG.error("An error occurred while processing your payment"); response.setErrorMessage("Something went wrong with payment processing"); } } sqlSession.commit(); } catch (ServiceException ex) { response.setErrorMessage(ex.getDetailedMessage()); sqlSession.getMapper(ReservationMapper.class).update(reservation); LOG.error(ex.getDetailedMessage()); if (reservationFinished) { sqlSession.commit(); } else { sqlSession.rollback(); } } catch (Throwable x) { x.printStackTrace(); response.setErrorMessage(x.getMessage()); sqlSession.getMapper(ReservationMapper.class).update(reservation); LOG.error(x.getMessage()); if (reservationFinished) { sqlSession.commit(); } else { sqlSession.rollback(); } } finally { sqlSession.close(); } try { sqlSession = RazorServer.openSession(); if (paymentTransaction != null) { sqlSession.getMapper(PaymentTransactionMapper.class).create(paymentTransaction); sqlSession.commit(); } } catch (Throwable x) { response.setErrorMessage(x.getMessage()); LOG.error(x.getMessage()); sqlSession.rollback(); } finally { sqlSession.close(); } try { sqlSession = RazorServer.openSession(); roundReservationDoubleValues(reservation); sendAdminEmail(sqlSession, paymentTransaction); } catch (Exception x) { if (!response.isError()) { response.setErrorMessage("Unable to round the values for reservation. :" + x.getMessage()); } LOG.error("Unable to round the values for reservation."); sqlSession.rollback(); } finally { sqlSession.close(); } response.setReservationInfo(new ReservationInfo(reservation)); return response; }
From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java
@Override public boolean removeExternalIDPUser(String fspId) throws Exception { // remove the FSP userId from default group ILdapConnectionEx connection = getConnection(); try {// w w w . j a v a 2 s. c o m String groupDN = String.format("cn=%s, %s", IdentityManager.WELLKNOWN_EXTERNALIDP_USERS_GROUP_NAME, getStoreDataEx().getGroupBaseDn()); String[] groupAttrNames = { ATTR_NAME_CN, ATTR_NAME_MEMBER }; ILdapMessage message = connection.search(groupDN, LdapScope.SCOPE_BASE, GROUP_ALL_PRINC_QUERY, groupAttrNames, false); try { ILdapEntry[] groupEntries = message.getEntries(); if (groupEntries == null || groupEntries.length != 1) { throw new IllegalStateException( String.format("group %s does not exist or duplicated", groupDN)); } // We found the group LdapValue[] values = groupEntries[0].getAttributeValues(ATTR_NAME_MEMBER); boolean memberFound = false; if (null != values) { for (LdapValue val : values) { String memberDn = val.toString(); if (0 == memberDn.compareToIgnoreCase(fspId)) { memberFound = true; break; } } } if (memberFound) { // If last sub-item in the group, we should remove // the member attribute since it is optional. LdapMod mod = new LdapMod(LdapModOperation.DELETE, ATTR_NAME_MEMBER, values.length == 1 ? null : fspId); // Update with new member list connection.modifyObject(groupEntries[0].getDN(), mod); } else { throw new InvalidPrincipalException( String.format("external IDP user %s is not registered", fspId), fspId); } } finally { message.close(); } } finally { connection.close(); } return true; }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
public ResolvedConceptReferencesIteratorWrapper searchByAssociations(Vector schemes, Vector versions, String matchText, String source, String matchAlgorithm, boolean designationOnly, boolean ranking, int maxToReturn) { if (matchText == null) return null; Vector codingSchemeNames = new Vector(); String matchText0 = matchText; String matchAlgorithm0 = matchAlgorithm; //matchText0 = matchText0.trim(); boolean containsMapping = false; _logger.debug("searchByAssociations..." + matchText); long ms = System.currentTimeMillis(); long dt = 0;/*from www . ja va 2 s. c o m*/ long total_delay = 0; boolean timeout = false; boolean preprocess = true; //if (matchText == null || matchText.length() == 0) { if (matchText.length() == 0) { return null; } matchText = matchText.trim(); if (matchAlgorithm.compareToIgnoreCase("contains") == 0) { // matchAlgorithm = Constants.CONTAIN_SEARCH_ALGORITHM; // to be // replaced by literalSubString matchAlgorithm = findBestContainsAlgorithm(matchText); } CodedNodeSet cns = null; ResolvedConceptReferencesIterator iterator = null; String scheme = null; String version = null; String message = null; try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } Vector cns_vec = new Vector(); for (int i = 0; i < schemes.size(); i++) { cns = null; iterator = null; scheme = (String) schemes.elementAt(i); _logger.debug("\tsearching " + scheme); ms = System.currentTimeMillis(); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); version = (String) versions.elementAt(i); if (version != null) versionOrTag.setVersion(version); // i++; try { // KLO, 022410 change failed //cns = lbSvc.getNodeSet(scheme, versionOrTag, null); cns = getNodeSet(lbSvc, scheme, versionOrTag); // cns = getNodeSetByEntityType(scheme, versionOrTag, // "concept"); if (cns != null) { try { // find cns if (designationOnly) { try { cns = cns.restrictToMatchingDesignations(matchText, null, matchAlgorithm, null); } catch (Exception ex) { ex.printStackTrace(); return null; } } cns = restrictToSource(cns, source); String associationName = null; int direction = RESTRICT_TARGET; // CodedNodeGraph cng = // getRestrictedCodedNodeGraph(lbSvc, scheme, // version, associationName, cns, direction); // toNode boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; // int maxToReturn = -1; ConceptReference graphFocus = null; // CodedNodeSet cns2 = cng.toNodeList(graphFocus, // resolveForward, resolveBackward, // resolveAssociationDepth, maxToReturn); // CodedNodeSet difference(CodedNodeSet // codesToRemove) // cns = cns2.difference(cns); //if (cns != null) { /* cns = filterOutAnonymousClasses(lbSvc, scheme, cns); */ //if (cns != null) { cns_vec.add(cns); codingSchemeNames.add(scheme); if (!containsMapping) { boolean isMapping = DataUtils.isMapping(scheme, null); if (isMapping) { containsMapping = true; } } //} //} } catch (Exception ex) { // return null; } } } catch (Exception e) { e.printStackTrace(); // return null; } dt = System.currentTimeMillis() - ms; ms = System.currentTimeMillis(); total_delay = total_delay + dt; //if (total_delay > (long) (NCItBrowserProperties.getPaginationTimeOut() * 60 * 1000)) { if (total_delay > Constants.MILLISECONDS_PER_MINUTE * NCItBrowserProperties.getPaginationTimeOut()) { message = "WARNING: Search is incomplete -- please enter more specific search criteria."; // cont_flag = false; break; } } iterator = null; if (cns_vec.size() == 0) { return null; } /* * cns = union(cns_vec); if (cns == null) return null; */ LocalNameList restrictToProperties = null;// new LocalNameList(); // boolean resolveConcepts = true; // if (!ranking) resolveConcepts = false; boolean resolveConcepts = false; SortOptionList sortCriteria = null; if (ranking) { sortCriteria = Constructors.createSortOptionList(new String[] { "matchToQuery" }); } else { sortCriteria = Constructors.createSortOptionList(new String[] { "entityDescription" }); // code _logger.debug("*** Sort alphabetically..."); // resolveConcepts = false; } // Need to set to true to retrieve concept name resolveConcepts = true; try { try { boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; // iterator = cns.resolve(sortCriteria, null, // restrictToProperties, null, resolveConcepts); if (!containsMapping) { ResolvedConceptReferencesIterator quickUnionIterator = new QuickUnionIterator(cns_vec, sortCriteria, null, restrictToProperties, null, resolveConcepts); /* try { int quickIteratorNumberRemaining = quickUnionIterator.numberRemaining(); } catch (Exception ex) { ex.printStackTrace(); } */ /* iterator = new SearchByAssociationIteratorDecorator( quickUnionIterator, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); */ iterator = createSearchByAssociationIteratorDecorator(quickUnionIterator, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); } else { ResolvedConceptReferencesIterator quickUnionIteratorWrapper = new QuickUnionIteratorWrapper( codingSchemeNames, cns_vec, sortCriteria, null, restrictToProperties, null, resolveConcepts); /* iterator = new SearchByAssociationIteratorDecorator( QuickUnionIteratorWrapper, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); */ iterator = createSearchByAssociationIteratorDecorator(quickUnionIteratorWrapper, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); } } catch (Exception e) { _logger.error("Method: SearchUtil.searchByAssociations"); _logger.error("* ERROR: cns.resolve throws exceptions."); _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } // Pending LexEVS fix: // if (iterator != null) iterator.setMessage(message); // return iterator; return new ResolvedConceptReferencesIteratorWrapper(iterator, message); }
From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java
@Override public boolean addGroupToGroup(PrincipalId groupId, String groupName) throws Exception { ValidateUtil.validateNotNull(groupId, "groupId"); ValidateUtil.validateNotEmpty(groupName, "groupName"); boolean added = false; String subGroupDn = null;// w w w . j a v a 2 s. co m String filter = null; String searchDn = null; ILdapConnectionEx connection = getConnection(); try { if (this.isSameDomainUpn(groupId)) { // Find the group to add String[] attrNames = { ATTR_NAME_CN }; filter = buildQueryByGroupFilter(groupId.getName()); // Check if searchDn should be revised searchDn = getTenantSearchBaseRootDN(); ILdapMessage subGroupMessage = connection.search(searchDn, LdapScope.SCOPE_SUBTREE, filter, attrNames, false); try { ILdapEntry[] entries = subGroupMessage.getEntries(); if (entries == null || entries.length != 1) { // Group doesn't exist or multiple user same name throw new InvalidPrincipalException( String.format("group %s doesn't exist or multiple users with same name", groupId.getName()), ServerUtils.getUpn(groupId)); } subGroupDn = entries[0].getDN(); } finally { subGroupMessage.close(); } } // Handle FSPs else { subGroupDn = groupId.getName(); } // Find the group to add a sub-group to String[] groupAttrNames = { ATTR_NAME_CN, ATTR_NAME_MEMBER }; filter = buildQueryByGroupFilter(groupName); searchDn = getTenantSearchBaseRootDN(); ILdapMessage groupMessage = connection.search(searchDn, LdapScope.SCOPE_SUBTREE, filter, groupAttrNames, false); try { ILdapEntry[] entries = groupMessage.getEntries(); // Check if multiple group same name but different level // We probably should check the searchbaseDN if (entries == null || entries.length != 1) { throw new InvalidPrincipalException( String.format("group %s doesn't exist or multiple groups same name", groupName), ServerUtils.getUpn(groupName, getDomain())); } // to prevent adding group to itself. if (subGroupDn.equalsIgnoreCase(entries[0].getDN())) { throw new InvalidArgumentException( String.format("Group %s cannot be added to itself.", groupId.getName())); } // We found the group LdapValue[] values = entries[0].getAttributeValues(ATTR_NAME_MEMBER); LdapMod attrMember = null; ArrayList<LdapValue> newValues = new ArrayList<LdapValue>(); if (null == values) { // This is the first sub-item for that group // add the new member to that group // Attribute "member" is optional in Lotus newValues.add(LdapValue.fromString(subGroupDn)); attrMember = new LdapMod(LdapModOperation.ADD, ATTR_NAME_MEMBER, newValues.toArray(new LdapValue[newValues.size()])); } else { for (LdapValue val : values) { String memberDn = val.toString(); // Not to add the member already in the group if (0 == memberDn.compareToIgnoreCase(subGroupDn)) { // Admin api states if already in the group // should return false. // Therefore, setting true here for the found // case. throw new MemberAlreadyExistException(String .format("group %s already has group %s as its member", groupName, subGroupDn)); } newValues.add(val); } // add the new member to that group newValues.add(LdapValue.fromString(subGroupDn)); attrMember = new LdapMod(LdapModOperation.REPLACE, ATTR_NAME_MEMBER, newValues.toArray(new LdapValue[newValues.size()])); } LdapMod attributes[] = { attrMember }; // Update with new member list // Today Lotus allows circular groups such as GroupA // contains GroupB and GroupB can contain GroupA again. // This isn't allowed for the admin api. Need to revisit to // see if check needs to be done here or can get the feature // from lotus. connection.modifyObject(entries[0].getDN(), attributes); added = true; } finally { groupMessage.close(); } } finally { connection.close(); } return added; }