@Override public DetachedCriteria getCriteria() { DetachedCriteria crit = getParent().getCriteria(); Junction junction = null; if (disjunction) { junction = Restrictions.disjunction(); } else { junction = Restrictions.conjunction(); } for (Iterator iter = attributeExpressions.iterator(); iter.hasNext();) { AttributeExpression aExpr = (AttributeExpression) iter.next(); DetachedCriteria attrCriteria = aExpr.getCriteria(); junction.add(Property.forName("longId").in(attrCriteria.setProjection(Projections.property("ownerId")))); } crit.add(junction); return(crit); }
/** * Complements a criteria by processing an enumeration query structure. * * @param path * the path to the comparable property. * @param enumQueryStructure * the collection of checked / unchecked enumeration values. * @return the created criterion or null if no criterion necessary. */ protected Criterion createEnumQueryStructureRestriction(String path, EnumQueryStructure enumQueryStructure) { Set<String> inListValues = new HashSet<>(); boolean nullAllowed = false; for (EnumValueQueryStructure inListValue : enumQueryStructure.getSelectedEnumerationValues()) { if (inListValue.getValue() == null || "".equals(inListValue.getValue())) { nullAllowed = true; } else { inListValues.add(inListValue.getValue()); } } Junction queryStructureRestriction = null; if (!inListValues.isEmpty() || nullAllowed) { queryStructureRestriction = Restrictions.disjunction(); if (!inListValues.isEmpty()) { queryStructureRestriction.add(Restrictions.in(path, inListValues)); } if (nullAllowed) { queryStructureRestriction.add(Restrictions.isNull(path)); } } return queryStructureRestriction; }
private Junction getDatumJunction(AdvancedSampleSearchBean searchBean) { // if AND and more than one type of datum, don't use junction if (searchBean.getCharacterizationLogicalOperator().equals("and") && searchBean.getDatumTypeCount() > 1) { return null; } Disjunction datumDisjunction = Restrictions.disjunction(); Conjunction datumConjunction = Restrictions.conjunction(); for (CharacterizationQueryBean charQuery : searchBean .getCharacterizationQueries()) { Criterion datumCrit = getDatumCriterion(charQuery); if (datumCrit != null) { datumDisjunction.add(datumCrit); if (searchBean.getDatumTypeCount() == 1) { datumConjunction.add(datumCrit); } } } // default to or if only one query Junction junction = (searchBean.getCharacterizationLogicalOperator() .equals("or") || searchBean.getCharacterizationQueries().size() == 1) ? datumDisjunction : datumConjunction; return junction; }
/** * Get the sample name junction used in sample queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getSampleNameJunction(AdvancedSampleSearchBean searchBean) throws Exception { Disjunction sampleDisjunction = Restrictions.disjunction(); Conjunction sampleConjunction = Restrictions.conjunction(); for (SampleQueryBean query : searchBean.getSampleQueries()) { if (query.getNameType().equals("sample name")) { Criterion sampleNameCrit = getSampleNameCriterion(query); if (sampleNameCrit != null) { sampleDisjunction.add(sampleNameCrit); sampleConjunction.add(sampleNameCrit); } } } Junction junction = (searchBean.getSampleLogicalOperator().equals("or") || searchBean .getSampleQueries().size() == 1) ? sampleDisjunction : sampleConjunction; return junction; }
public boolean applySearchFilters(Criteria criteria, String searchTerm) { boolean filterAdded = false; //If search string is integer type, it only searches on Id field if (NumberUtils.isDigits(searchTerm)) { criteria.add(Restrictions.eq(getIdField(), Integer.parseInt(searchTerm))); filterAdded = true; } else if (getSearchFields() != null && getSearchFields().size() != 0) { //Text filtering is applied only if you have specified getSearchFields(). String likeTerm = "%" + searchTerm + "%"; Junction disjunction = Restrictions.disjunction(); for (String field : getSearchFields()) { //Performs case insensitive search on all search fields. //Also does not searches on associations. Only value types are searched. disjunction.add(Restrictions.ilike(field, likeTerm)); } criteria.add(disjunction); filterAdded = true; } return filterAdded; }
private void addChromosomeCoordinatesToCriterion(Integer chromosomeCoordinateHigh, Integer chromosomeCoordinateLow, Criteria segmentDataCrit, String chromosomeNumber) { if (chromosomeCoordinateHigh == null || chromosomeCoordinateLow == null) { segmentDataCrit.add(chromosomeNumberExpression(chromosomeNumber)); if (chromosomeCoordinateHigh != null) { segmentDataCrit.add(segmentEndLessThanHigh(chromosomeCoordinateHigh)); } if (chromosomeCoordinateLow != null) { segmentDataCrit.add(segmentStartGreaterThanLow(chromosomeCoordinateLow)); } } else { Junction overallOrStatement = Restrictions.disjunction(); // (loc.startPos <= lowerInput && loc.endPos >= lowerInput && loc.chromosome == chromosomeInput) // || (loc.startPos >= lowerInput && loc.startPos <= higherInput && loc.chromosome == chromosomeInput) overallOrStatement.add(Restrictions.conjunction().add(segmentStartLessThanLow(chromosomeCoordinateLow)) .add(segmentEndGreaterThanLow(chromosomeCoordinateLow)).add( chromosomeNumberExpression(chromosomeNumber))); overallOrStatement.add(Restrictions.conjunction().add(segmentStartGreaterThanLow(chromosomeCoordinateLow)) .add(segmentStartLessThanHigh(chromosomeCoordinateHigh)).add( chromosomeNumberExpression(chromosomeNumber))); segmentDataCrit.add(overallOrStatement); } }
private void addMultipleChromosomeCoordinatesToCriterion(Criteria segmentDataCrit, List<GeneChromosomalLocation> geneLocations) { Junction overallOrStatement = Restrictions.disjunction(); // (loc.startPos <= lowerInput && loc.endPos >= lowerInput && loc.chromosome == chromosomeInput) // || (loc.startPos >= lowerInput && loc.startPos <= higherInput && loc.chromosome == chromosomeInput) for (GeneChromosomalLocation geneLocation : geneLocations) { Integer chromosomeCoordinateLow = geneLocation.getLocation().getStartPosition(); Integer chromosomeCoordinateHigh = geneLocation.getLocation().getEndPosition(); overallOrStatement.add(Restrictions.conjunction().add(segmentStartLessThanLow(chromosomeCoordinateLow)) .add(segmentEndGreaterThanLow(chromosomeCoordinateLow)).add( chromosomeNumberExpression(Cai2Util.getInternalChromosomeNumber( geneLocation.getLocation().getChromosome())))); overallOrStatement.add(Restrictions.conjunction().add(segmentStartGreaterThanLow(chromosomeCoordinateLow)) .add(segmentStartLessThanHigh(chromosomeCoordinateHigh)).add( chromosomeNumberExpression(Cai2Util.getInternalChromosomeNumber( geneLocation.getLocation().getChromosome())))); } segmentDataCrit.add(overallOrStatement); }
/** * {@inheritDoc} */ @Override @SuppressWarnings(UNCHECKED) // Hibernate operations are untyped public List<SegmentData> findMatchingSegmentDatasByLocation(List<SegmentData> segmentDatasToMatch, Study study, Platform platform) { Criteria segmentDataCrit = getCurrentSession().createCriteria(SegmentData.class); Criteria arrayDataCrit = segmentDataCrit.createCriteria("arrayData"); Criteria reporterListsCrit = arrayDataCrit.createCriteria("reporterLists"); reporterListsCrit.add(Restrictions.eq(PLATFORM_ASSOCIATION, platform)); arrayDataCrit.add(Restrictions.eq(STUDY_ASSOCIATION, study)); Junction overallOrStatement = Restrictions.disjunction(); for (SegmentData segmentData : segmentDatasToMatch) { ChromosomalLocation location = segmentData.getLocation(); overallOrStatement.add(Restrictions.conjunction(). add(Restrictions.eq("Location.startPosition", location.getStartPosition())). add(Restrictions.eq("Location.endPosition", location.getEndPosition()))); } segmentDataCrit.add(overallOrStatement); return segmentDataCrit.list(); }
private static boolean applyCategoryCriterion(Object criteriaJunction, CategoryCriterion categoryCriterion) { Criterion restriction = getCategoryCriterionRestriction(categoryCriterion); if (restriction != null) { if (criteriaJunction instanceof Criteria) { ((Criteria) criteriaJunction).add(restriction); return true; } else if (criteriaJunction instanceof Junction) { ((Junction) criteriaJunction).add(restriction); return true; } } return false; }
private static void applyCategoryCriterions(Criteria criteria, Junction junction, CategoryCriterion... categoryCriterions) { if (criteria != null && junction != null && categoryCriterions != null) { if (categoryCriterions.length > 0) { boolean applied = false; for (int i = 0; i < categoryCriterions.length; i++) { applied |= applyCategoryCriterion(junction, categoryCriterions[i]); } if (applied) { criteria.add(junction); } } } }
private Criterion createCriterion(CriteriaWrapper crit, AndOrPredicate pred, String contextAlias) { Operator op = pred.getOperator(); Junction junction = (op == Operator.And) ? Restrictions.conjunction() : Restrictions.disjunction(); for (Predicate subPred : pred.getPredicates()) { Criterion cr = toCriterion(crit, subPred, contextAlias); junction.add(cr); } return junction; }
@Override public void visitAllComplete(final AllRestriction restriction) { final int restrictionSize = restriction.getRestrictions().size(); final int criterionSize = m_criterions.size(); if (criterionSize < restrictionSize) { throw new IllegalStateException("AllRestriction with " + restrictionSize + " entries encountered, but we only have " + criterionSize + " criterions!"); } final List<Criterion> criterions = m_criterions.subList(criterionSize - restrictionSize, criterionSize); final Junction j = org.hibernate.criterion.Restrictions.conjunction(); for (final Criterion crit : criterions) { j.add(crit); } criterions.clear(); m_criterions.add(j); }
@Override public void visitAnyComplete(final AnyRestriction restriction) { final int restrictionSize = restriction.getRestrictions().size(); final int criterionSize = m_criterions.size(); if (criterionSize < restrictionSize) { throw new IllegalStateException("AllRestriction with " + restrictionSize + " entries encountered, but we only have " + criterionSize + " criterions!"); } final List<Criterion> criterions = m_criterions.subList(criterionSize - restrictionSize, criterionSize); final Junction j = org.hibernate.criterion.Restrictions.disjunction(); for (final Criterion crit : criterions) { j.add(crit); } criterions.clear(); m_criterions.add(j); }
/** * Get the junction used in function queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getFunctionJunction(AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { // if AND and more than one query per type, don't use junction if (searchBean.getCompositionLogicalOperator().equals("and") && searchBean.getFuncCount() > 1) { return null; } Disjunction compDisjunction = Restrictions.disjunction(); Conjunction compConjunction = Restrictions.conjunction(); for (CompositionQueryBean compQuery : searchBean .getCompositionQueries()) { // function if (compQuery.getCompositionType().equals("function")) { Criterion funcCrit = this.getFunctionCriterion(compQuery, "", ""); if (funcCrit != null) { compDisjunction.add(funcCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getFuncCount() == 1) { compConjunction.add(funcCrit); } } } } // default to or if only one query Junction junction = (searchBean.getCompositionLogicalOperator().equals( "or") || searchBean.getCompositionQueries().size() == 1) ? compDisjunction : compConjunction; return junction; }
/** * Get the junction used in nanomaterial entity queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getNanomaterialEntityJunction( AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { // if AND and more than one query per type, don't use junction if (searchBean.getCompositionLogicalOperator().equals("and") && searchBean.getNanoEntityCount() > 1) { return null; } Disjunction compDisjunction = Restrictions.disjunction(); Conjunction compConjunction = Restrictions.conjunction(); for (CompositionQueryBean compQuery : searchBean .getCompositionQueries()) { // nanomaterial entity if (compQuery.getCompositionType().equals("nanomaterial entity")) { Criterion nanoEntityCrit = getNanomaterialEntityCriterion( compQuery, ""); if (nanoEntityCrit != null) { compDisjunction.add(nanoEntityCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getNanoEntityCount() == 1) { compConjunction.add(nanoEntityCrit); } } } } // default to or if only one query Junction junction = (searchBean.getCompositionLogicalOperator().equals( "or") || searchBean.getCompositionQueries().size() == 1) ? compDisjunction : compConjunction; return junction; }
/** * Get the junction used in functionalizing entity queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getFunctionalizingEntityJunction( AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { // if AND and more than one query per type, don't use junction if (searchBean.getCompositionLogicalOperator().equals("and") && searchBean.getFuncEntityCount() > 1) { return null; } Disjunction compDisjunction = Restrictions.disjunction(); Conjunction compConjunction = Restrictions.conjunction(); for (CompositionQueryBean compQuery : searchBean .getCompositionQueries()) { // functionalizing entity if (compQuery.getCompositionType().equals("functionalizing entity")) { Criterion funcEntityCrit = getFunctionalizingEntityCriterion( compQuery, ""); if (funcEntityCrit != null) { compDisjunction.add(funcEntityCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getFuncEntityCount() == 1) { compConjunction.add(funcEntityCrit); } } } } // default to or if only one query Junction junction = (searchBean.getCompositionLogicalOperator().equals( "or") || searchBean.getCompositionQueries().size() == 1) ? compDisjunction : compConjunction; return junction; }
/** * Get the sample disjunction used in sample queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getSampleJunction(AdvancedSampleSearchBean searchBean) throws Exception { // if there are more than one POC query in AND, don't use junction. if (searchBean.getSampleLogicalOperator().equals("and") && searchBean.getPocCount() > 1) { return null; } Disjunction sampleDisjunction = Restrictions.disjunction(); Conjunction sampleConjunction = Restrictions.conjunction(); for (SampleQueryBean query : searchBean.getSampleQueries()) { if (query.getNameType().equals("sample name")) { Criterion sampleNameCrit = getSampleNameCriterion(query); if (sampleNameCrit != null) { sampleDisjunction.add(sampleNameCrit); sampleConjunction.add(sampleNameCrit); } } if (query.getNameType().equals("point of contact name")) { Disjunction pocDisjunction = getPointOfContactDisjunction( searchBean, "poc.", "otherPOC."); if (pocDisjunction != null) { sampleDisjunction.add(pocDisjunction); if (searchBean.getPocCount() == 1) { sampleConjunction.add(pocDisjunction); } } } } Junction junction = (searchBean.getSampleLogicalOperator().equals("or") || searchBean .getSampleQueries().size() == 1) ? sampleDisjunction : sampleConjunction; return junction; }
/** * Set the DetachedCriteria for sample queries * * @param searchBean * @param crit * @throws Exception */ private void setSampleCriteria(AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { if (searchBean.getSampleQueries().isEmpty()) { return; } // join POC if (searchBean.getHasPOC()) { crit.createAlias("primaryPointOfContact", "poc"); crit.createAlias("poc.organization", "organization"); crit.createAlias("otherPointOfContactCollection", "otherPOC", CriteriaSpecification.LEFT_JOIN); crit.createAlias("otherPOC.organization", "otherOrg", CriteriaSpecification.LEFT_JOIN); } Junction junction = getSampleJunction(searchBean); if (junction != null) { crit.add(junction); } // more than one POC and AND else { crit.add(getSampleNameJunction(searchBean)); for (SampleQueryBean query : searchBean.getSampleQueries()) { if (query.getNameType().equals("point of contact name")) { DetachedCriteria subCrit = getPointOfContactSubquery(query, "poc.", "otherPOC.", "id"); crit.add(Subqueries.exists(subCrit)); } } } }
/** * @param criterion * @see #visit(edu.utah.further.core.data.search.JunctionCriterionImpl) */ public void visitJunction() { final SearchType searchType = criterion.getSearchType(); switch (searchType) { case CONJUNCTION: { result = Restrictions.conjunction(); break; } case DISJUNCTION: { result = Restrictions.disjunction(); break; } default: { throw new BusinessRuleException(unsupportedMessage(searchType)); } } // Add junction arguments for (final Criterion c : convertedCriteria) { ((Junction) result).add(c); } }
private void addAnnotationCriterionValues(Criteria c, Junction junction, Set<String> values, String assocPath, String alias) { if (!values.isEmpty()) { c.createAlias(assocPath, alias); junction.add(Restrictions.in(alias + ".value", values)); } }
@Test public void or() { Criterion o1 = Restrictions.eq(property, value); Criterion o2 = Restrictions.in(property, values); Criterion o3 = Restrictions.lt(property, value); Junction expected = Restrictions.disjunction().add(o1).add(o2).add(o3); assertEquivalent(expected, translator.or(o1, o2, o3)); }
@Test public void and() { Criterion o1 = Restrictions.eq(property, value); Criterion o2 = Restrictions.in(property, values); Criterion o3 = Restrictions.lt(property, value); Junction expected = Restrictions.conjunction().add(o1).add(o2).add(o3); assertEquivalent(expected, translator.and(o1, o2, o3)); }
/** * {@inheritDoc} */ @Override @SuppressWarnings(UNCHECKED) // Hibernate operations are untyped public List<Gene> findGenesByLocation(String chromosome, Integer startPosition, Integer endPosition, GenomeBuildVersionEnum genomeBuildVersion) { String locStartPosition = "location.startPosition"; String locEndPosition = "location.endPosition"; Criteria geneLocationCriteria = getCurrentSession().createCriteria(GeneChromosomalLocation.class); // (gene.startPos <= startPosition && gene.endPos >= startPosition) // || (gene.startPos >= lowerInput && gene.startPos <= higherInput) Junction overallOrStatement = Restrictions.disjunction(); overallOrStatement.add(Restrictions.conjunction().add(Restrictions.le(locStartPosition, startPosition)) .add(Restrictions.ge(locEndPosition, startPosition))); overallOrStatement.add(Restrictions.conjunction().add(Restrictions.ge(locStartPosition, startPosition)).add( Restrictions.le(locStartPosition, endPosition))); geneLocationCriteria.add(overallOrStatement); geneLocationCriteria.add(getChromosomeRestriction(chromosome)); geneLocationCriteria.createCriteria("geneLocationConfiguration"). add(Restrictions.eq("genomeBuildVersion", genomeBuildVersion)); geneLocationCriteria.setProjection(Projections.property("geneSymbol")); List<String> geneSymbols = geneLocationCriteria.list(); return geneSymbols.isEmpty() ? new ArrayList<Gene>() : getCurrentSession().createCriteria(Gene.class).setProjection( Projections.distinct(Projections.property(SYMBOL_ATTRIBUTE))). add(Restrictions.in(SYMBOL_ATTRIBUTE, geneSymbols)). addOrder(Order.asc(SYMBOL_ATTRIBUTE)).list(); }
/** * Complete criteria with translations. * * @param currentCriteria * the current criteria * @param translationsPath * the translations path * @param translationsAlias * the translations alias * @param property * the property * @param propertyDescriptor * the property descriptor * @param prefixedProperty * the prefixed property * @param locale * the locale * @param componentDescriptor * the component descriptor * @param queryComponent * the query component * @param context * the context */ @SuppressWarnings("unchecked") protected void completeCriteriaWithTranslations(DetachedCriteria currentCriteria, String translationsPath, String translationsAlias, Map.Entry<String, Object> property, IPropertyDescriptor propertyDescriptor, String prefixedProperty, Locale locale, IComponentDescriptor<?> componentDescriptor, IQueryComponent queryComponent, Map<String, Object> context) { if (propertyDescriptor instanceof IStringPropertyDescriptor && ((IStringPropertyDescriptor) propertyDescriptor) .isTranslatable()) { String nlsOrRawValue = null; String nlsValue = (String) property.getValue(); String barePropertyName = property.getKey(); if (property.getKey().endsWith(IComponentDescriptor.NLS_SUFFIX)) { barePropertyName = barePropertyName.substring(0, barePropertyName.length() - IComponentDescriptor.NLS_SUFFIX.length()); } else { nlsOrRawValue = nlsValue; } if (nlsValue != null) { Junction translationRestriction = Restrictions.conjunction(); translationRestriction.add(createStringRestriction( ((ICollectionPropertyDescriptor<IPropertyTranslation>) componentDescriptor.getPropertyDescriptor( translationsPath)).getCollectionDescriptor().getElementDescriptor().getPropertyDescriptor( IPropertyTranslation.TRANSLATED_VALUE), translationsAlias + "." + IPropertyTranslation.TRANSLATED_VALUE, nlsValue, componentDescriptor, queryComponent, context)); String languagePath = translationsAlias + "." + IPropertyTranslation.LANGUAGE; translationRestriction.add(Restrictions.eq(languagePath, locale.getLanguage())); translationRestriction.add(Restrictions.eq(translationsAlias + "." + IPropertyTranslation.PROPERTY_NAME, barePropertyName)); Junction disjunction = Restrictions.disjunction(); disjunction.add(translationRestriction); if (nlsOrRawValue != null) { Junction rawValueRestriction = Restrictions.conjunction(); rawValueRestriction.add(Restrictions.disjunction().add(Restrictions.isNull(languagePath)).add(Restrictions.ne( languagePath, locale.getLanguage()))); String rawPropertyName = barePropertyName + IComponentDescriptor.RAW_SUFFIX; rawValueRestriction.add(createStringRestriction(componentDescriptor.getPropertyDescriptor(rawPropertyName), rawPropertyName, nlsOrRawValue, componentDescriptor, queryComponent, context)); disjunction.add(rawValueRestriction); } currentCriteria.add(disjunction); } } else { completeCriteria(currentCriteria, createStringRestriction(propertyDescriptor, prefixedProperty, (String) property.getValue(), componentDescriptor, queryComponent, context)); } }
/** * Creates a string based restriction. * * @param propertyDescriptor * the property descriptor. * @param prefixedProperty * the full path of the property. * @param propertyValue * the string property value. * @param componentDescriptor * the component descriptor * @param queryComponent * the query component * @param context * the context * @return the created criterion or null if no criterion necessary. */ protected Criterion createStringRestriction(IPropertyDescriptor propertyDescriptor, String prefixedProperty, String propertyValue, IComponentDescriptor<?> componentDescriptor, IQueryComponent queryComponent, Map<String, Object> context) { Junction disjunction = null; if (propertyValue.length() > 0) { String[] stringDisjunctions = propertyValue.split(IQueryComponent.DISJUNCT); disjunction = Restrictions.disjunction(); for (String stringDisjunction : stringDisjunctions) { Junction conjunction = Restrictions.conjunction(); String[] stringConjunctions = stringDisjunction.split(IQueryComponent.CONJUNCT); for (String stringConjunction : stringConjunctions) { String val = stringConjunction; if (val.length() > 0) { Criterion crit; boolean negate = false; if (val.startsWith(IQueryComponent.NOT_VAL)) { val = val.substring(1); negate = true; } if (IQueryComponent.NULL_VAL.equals(val)) { crit = Restrictions.isNull(prefixedProperty); } else { if (IEntity.ID.equals(propertyDescriptor.getName()) || propertyDescriptor instanceof IEnumerationPropertyDescriptor) { crit = Restrictions.eq(prefixedProperty, val); } else { crit = createLikeRestriction(propertyDescriptor, prefixedProperty, val, componentDescriptor, queryComponent, context); } } if (negate) { crit = Restrictions.not(crit); } conjunction.add(crit); } } disjunction.add(conjunction); } } return disjunction; }
/** * Creates a criterion by processing a comparable query structure. * * @param path * the path to the comparable property. * @param queryStructure * the comparable query structure. * @param componentDescriptor * the component descriptor * @param queryComponent * the query component * @param context * the context * @return the created criterion or null if no criterion necessary. */ protected Criterion createComparableQueryStructureRestriction(String path, ComparableQueryStructure queryStructure, IComponentDescriptor<?> componentDescriptor, IQueryComponent queryComponent, Map<String, Object> context) { Junction queryStructureRestriction = null; if (queryStructure.isRestricting()) { queryStructureRestriction = Restrictions.conjunction(); String comparator = queryStructure.getComparator(); Object infValue = queryStructure.getInfValue(); Object supValue = queryStructure.getSupValue(); Object compareValue = infValue; if (compareValue == null) { compareValue = supValue; } switch (comparator) { case ComparableQueryStructureDescriptor.EQ: queryStructureRestriction.add(Restrictions.eq(path, compareValue)); break; case ComparableQueryStructureDescriptor.GT: queryStructureRestriction.add(Restrictions.gt(path, compareValue)); break; case ComparableQueryStructureDescriptor.GE: queryStructureRestriction.add(Restrictions.ge(path, compareValue)); break; case ComparableQueryStructureDescriptor.LT: queryStructureRestriction.add(Restrictions.lt(path, compareValue)); break; case ComparableQueryStructureDescriptor.LE: queryStructureRestriction.add(Restrictions.le(path, compareValue)); break; case ComparableQueryStructureDescriptor.NU: queryStructureRestriction.add(Restrictions.isNull(path)); break; case ComparableQueryStructureDescriptor.NN: queryStructureRestriction.add(Restrictions.isNotNull(path)); break; case ComparableQueryStructureDescriptor.BE: if (infValue != null && supValue != null) { queryStructureRestriction.add(Restrictions.between(path, infValue, supValue)); } else if (infValue != null) { queryStructureRestriction.add(Restrictions.ge(path, infValue)); } else { queryStructureRestriction.add(Restrictions.le(path, supValue)); } break; default: break; } } return queryStructureRestriction; }
private static Junction buildQueryWithKeywords(List<Keyword> words, int target, boolean any) { final String[] targetColumns = { null, "TAG_NAME", "TITLE", "CONTENT", "this_.FRAGMENT_ID" }; final String column = targetColumns[target]; if (column == null) { throw new IllegalArgumentException(); } final Junction junction = any ? Restrictions.disjunction() : Restrictions.conjunction(); for (SearchParams.Keyword w : words) { final Pair<String, Character> tmp = getPatternFromKeyword(w); final String pattern = tmp.getFirst(); final char escapeChar = tmp.getSecond(); String sql = null; if (w.isTrivial()) { if (w.isCaseSensitive()) { sql = column + " like " + "'" + pattern + "'"; } else { sql = "lower(" + column + ") like " + "'" + pattern.toLowerCase() + "'"; } if (escapeChar != 0) { sql += " escape '" + escapeChar + "'"; } } else { if (w.isId()) { sql = column + " = " + pattern; } else if (w.isRegex()) { sql = column + " regexp " + "'" + pattern + "'"; } else if (w.isWholeWord()) { if (w.isCaseSensitive()) { sql = column + " regexp " + "'\\b" + pattern + "\\b'"; } else { sql = "lower(" + column + ") regexp " + "'\\b" + pattern.toLowerCase() + "\\b'"; } } else if (w.isBeginningWith()) { if (w.isCaseSensitive()) { sql = column + " regexp " + "'\\b" + pattern + "'"; } else { sql = "lower(" + column + ") regexp " + "'\\b" + pattern.toLowerCase() + "'"; } } else if (w.isEndingWith()) { if (w.isCaseSensitive()) { sql = column + " regexp " + "'" + pattern + "\\b'"; } else { sql = "lower(" + column + ") regexp " + "'" + pattern.toLowerCase() + "\\b'"; } } else { throw new UnsupportedOperationException(); } } if (w.isInverse()) { sql = "not " + sql; } // [TODO] research compatibility issues with other DBMS vendors junction.add(Restrictions.sqlRestriction(sql)); } return junction; }
/** * Get the junction used in composition queries * * @param searchBean * @param crit * @return * @throws Exception */ private Junction getCompositionJunction( AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { // if AND and more than one query per type, don't use junction if (searchBean.getCompositionLogicalOperator().equals("and") && searchBean.getFuncCount() > 1 && searchBean.getNanoEntityCount() > 1 && searchBean.getFuncEntityCount() > 1) { return null; } Disjunction compDisjunction = Restrictions.disjunction(); Conjunction compConjunction = Restrictions.conjunction(); for (CompositionQueryBean compQuery : searchBean .getCompositionQueries()) { // function if (compQuery.getCompositionType().equals("function")) { Criterion funcCrit = this.getFunctionCriterion(compQuery, "inherentFunction.", "function."); if (funcCrit != null) { compDisjunction.add(funcCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getFuncCount() == 1) { compConjunction.add(funcCrit); } } } // nanomaterial entity else if (compQuery.getCompositionType().equals( "nanomaterial entity")) { Criterion nanoEntityCrit = getNanomaterialEntityCriterion( compQuery, "nanoEntity."); if (nanoEntityCrit != null) { compDisjunction.add(nanoEntityCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getNanoEntityCount() == 1) { compConjunction.add(nanoEntityCrit); } } } // functionalizing entity else if (compQuery.getCompositionType().equals( "functionalizing entity")) { Criterion funcEntityCrit = getFunctionalizingEntityCriterion( compQuery, "funcEntity."); if (funcEntityCrit != null) { compDisjunction.add(funcEntityCrit); // only add to conjunction if there is only one query for // the type if (searchBean.getFuncEntityCount() == 1) { compConjunction.add(funcEntityCrit); } } } } // default to or if only one query Junction junction = (searchBean.getCompositionLogicalOperator().equals( "or") || searchBean.getCompositionQueries().size() == 1) ? compDisjunction : compConjunction; return junction; }
/** * Set the DetachedCriteria used for composition queries * * @param searchBean * @param crit * @throws Exception */ private void setCompositionCriteriaBase(AdvancedSampleSearchBean searchBean, DetachedCriteria crit) throws Exception { if (searchBean.getCompositionQueries().isEmpty()) { return; } // composition queries crit.createAlias("sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN); Boolean hasChemicalName = searchBean.getHasChemicalName(); // join function if (searchBean.getHasFunction()) { crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN); crit.createAlias("nanoEntity.composingElementCollection", "compElement", CriteriaSpecification.LEFT_JOIN); crit.createAlias("compElement.inherentFunctionCollection", "inherentFunction", CriteriaSpecification.LEFT_JOIN); crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN); crit.createAlias("funcEntity.functionCollection", "function", CriteriaSpecification.LEFT_JOIN); } // join nanomaterialEntity if (searchBean.getHasNanomaterial() && !searchBean.getHasFunction()) { crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN); if (hasChemicalName) { crit.createAlias("nanoEntity.composingElementCollection", "compElement", CriteriaSpecification.LEFT_JOIN); } } // join functionalizing entity if (searchBean.getHasAgentMaterial() && !searchBean.getHasFunction()) { crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN); } Junction junction = getCompositionJunction(searchBean, crit); if (junction != null) { crit.add(junction); } /* if (searchBean.getNanoEntityCount() > 1) { setNanomaterialEntityAndCriteria(searchBean, crit, "id"); } if (searchBean.getFuncEntityCount() > 1) { setFunctionalizingEntityAndCriteria(searchBean, crit, "id"); } if (searchBean.getFuncCount() > 1) { setFunctionAndCriteria(searchBean, crit, "id"); } */ }
/** * @param request * @return * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest) */ @Override public boolean process(final ChainRequest request) { // Read input arguments final HibernateExecReq executionReq = new HibernateExecReq(request); final SessionFactory sessionFactory = executionReq.getSessionFactory(); notNull(sessionFactory, "Expected SessionFactory"); final Class<? extends PersistentEntity<?>> rootEntity = executionReq .getRootEntity(); notNull(rootEntity, "Expected root entity class"); // Read the search criteria's root entity meta data final List<Object> list = executionReq.getResult(); final Object[] listArray = CollectionUtil.toArrayNullSafe(list); final ClassMetadata classMetadata = sessionFactory.getClassMetadata(rootEntity); final String identifierName = classMetadata.getIdentifierPropertyName(); final Type identifierType = classMetadata.getIdentifierType(); final int numTypes = listArray.length; final Type[] types = new Type[numTypes]; for (int i = 0; i < numTypes; i++) { types[i] = identifierType; } // Build Hibernate criteria final GenericCriteria criteria = GenericCriteriaFactory.criteria( CriteriaType.CRITERIA, rootEntity, sessionFactory.getCurrentSession()); if (identifierType.isComponentType()) { final String sqlInClause = HibernateUtil.sqlRestrictionCompositeIn( rootEntity, sessionFactory, numTypes); criteria.add(Restrictions.sqlRestriction(sqlInClause, listArray, types)); } else { final int size = list.size(); if (size > MAX_IN) { // Create a disjunction of IN clauses. Add MAX_IN elements at a time to // each IN clause (except the last IN, whose size is size % MAX_IN). final Junction junction = Restrictions.disjunction(); for (int i = 0; i < size; i += MAX_IN) { junction.add(Restrictions.in(THIS + identifierName, list.subList(i, Math.max(size, MAX_IN + i)))); } criteria.add(junction); } else { // Single chunk, add directly as a criterion without the junction trick criteria.add(Restrictions.in(THIS + identifierName, list)); } } executionReq.setResult(criteria); return false; }
/** * {@inheritDoc} */ @SuppressWarnings({ "unchecked", "PMD" }) public <T extends AbstractBioMaterial> List<T> searchByCriteria(PageSortParams<T> params, BiomaterialSearchCriteria criteria) { Criteria c = getCurrentSession().createCriteria(AbstractBioMaterial.class); if (criteria.getExperiment() != null) { c.add(Restrictions.eq("experiment", criteria.getExperiment())); } if (!criteria.getNames().isEmpty()) { c.add(Restrictions.in("name", criteria.getNames())); } if (!criteria.getExternalIds().isEmpty()) { c.add(Restrictions.in("externalId", criteria.getExternalIds())); } if (!criteria.getBiomaterialClasses().isEmpty()) { // unfortunately due to a hibernate bug we have to explicitly specify discriminators // rather than being able to use classnames Set<String> discriminators = new HashSet<String>(); for (Class<? extends AbstractBioMaterial> bmClass : criteria.getBiomaterialClasses()) { discriminators.add(getDiscriminator(bmClass)); } c.add(Restrictions.in("class", discriminators)); } if (!criteria.getAnnotationCriterions().isEmpty()) { Set<String> diseaseStates = new HashSet<String>(); Set<String> tissueSites = new HashSet<String>(); Set<String> cellTypes = new HashSet<String>(); Set<String> materialTypes = new HashSet<String>(); for (AnnotationCriterion ac : criteria.getAnnotationCriterions()) { if (ac.getCategory().getName() .equals(ExperimentOntologyCategory.DISEASE_STATE.getCategoryName())) { diseaseStates.add(ac.getValue()); } else if (ac.getCategory().getName() .equals(ExperimentOntologyCategory.CELL_TYPE.getCategoryName())) { cellTypes.add(ac.getValue()); } else if (ac.getCategory().getName() .equals(ExperimentOntologyCategory.MATERIAL_TYPE.getCategoryName())) { materialTypes.add(ac.getValue()); } else if (ac.getCategory().getName() .equals(ExperimentOntologyCategory.ORGANISM_PART.getCategoryName())) { tissueSites.add(ac.getValue()); } } if (!diseaseStates.isEmpty() || !tissueSites.isEmpty() || !cellTypes.isEmpty() || !materialTypes.isEmpty()) { Junction and = Restrictions.conjunction(); addAnnotationCriterionValues(c, and, diseaseStates, "diseaseState", "ds"); addAnnotationCriterionValues(c, and, tissueSites, "tissueSite", "ts"); addAnnotationCriterionValues(c, and, materialTypes, "materialType", "mt"); addAnnotationCriterionValues(c, and, cellTypes, "cellType", "ct"); c.add(and); } } c.setFirstResult(params.getIndex()); if (params.getPageSize() > 0) { c.setMaxResults(params.getPageSize()); } c.addOrder(toOrder(params)); return c.list(); }