Example usage for org.hibernate.criterion DetachedCriteria createAlias

List of usage examples for org.hibernate.criterion DetachedCriteria createAlias

Introduction

In this page you can find the example usage for org.hibernate.criterion DetachedCriteria createAlias.

Prototype

public DetachedCriteria createAlias(String associationPath, String alias) 

Source Link

Document

Creates an association path alias within this DetachedCriteria.

Usage

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

private List<PointOfContact> findPointOfContactsBy(Sample sample, AdvancedSampleSearchBean searchBean)
        throws Exception {
    if (!searchBean.getHasPOC()) {
        return null;
    }//from   ww  w.  j  av a2 s .  c o m

    // get POCs associated with the sample
    List<PointOfContact> samplePOCs = new ArrayList<PointOfContact>();
    samplePOCs.add(sample.getPrimaryPointOfContact());
    samplePOCs.addAll(sample.getOtherPointOfContactCollection());
    List<PointOfContact> pocs = new ArrayList<PointOfContact>(samplePOCs);

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    if (searchBean.getCharacterizationQueries().size() == 1
            || searchBean.getSampleLogicalOperator().equals("or")) {
        DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
        crit.createAlias("organization", "organization");
        crit.add(getPointOfContactDisjunction(searchBean, "", ""));
        crit.setFetchMode("organization", FetchMode.JOIN);
        List results = appService.query(crit);
        for (int i = 0; i < results.size(); i++) {
            PointOfContact poc = (PointOfContact) results.get(i);
            // check if in sample POCs
            if (!samplePOCs.contains(poc)) {
                pocs.remove(poc);
            }
        }
    } else {
        for (SampleQueryBean query : searchBean.getSampleQueries()) {
            if (query.getNameType().equals("point of contact name")) {
                DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
                crit.createAlias("organization", "organization");
                DetachedCriteria subCrit = getPointOfContactSubquery(query, "", "", "id");
                crit.add(Subqueries.exists(subCrit));
                crit.setFetchMode("organization", FetchMode.JOIN);
                List results = appService.query(crit);
                for (int i = 0; i < results.size(); i++) {
                    PointOfContact poc = (PointOfContact) results.get(i);
                    // check if in sample POCs
                    if (!samplePOCs.contains(poc)) {
                        pocs.remove(poc);
                    }
                }
            }
        }
    }
    return pocs;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.AdvancedSampleServiceHelper.java

License:BSD License

/**
 * Set the DetachedCriteria for sample queries
 * // ww  w  .  j  ava  2  s  . c  o m
 * @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));
            }
        }
    }
}

From source file:gov.nih.nci.cananolab.service.sample.helper.CharacterizationServiceHelper.java

License:BSD License

public List<Characterization> findCharacterizationsBySampleId(String sampleId) throws Exception {
    List<Characterization> chars = new ArrayList<Characterization>();

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();/*from w  w w .  j ava 2s  . com*/
    DetachedCriteria crit = DetachedCriteria.forClass(Characterization.class);
    crit.createAlias("sample", "sample");
    crit.add(Property.forName("sample.id").eq(new Long(sampleId)));
    // fully load characterization
    crit.setFetchMode("pointOfContact", FetchMode.JOIN);
    crit.setFetchMode("pointOfContact.organization", FetchMode.JOIN);
    crit.setFetchMode("protocol", FetchMode.JOIN);
    crit.setFetchMode("protocol.file", FetchMode.JOIN);
    crit.setFetchMode("protocol.file.keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("experimentConfigCollection", FetchMode.JOIN);
    crit.setFetchMode("experimentConfigCollection.technique", FetchMode.JOIN);
    crit.setFetchMode("experimentConfigCollection.instrumentCollection", FetchMode.JOIN);
    crit.setFetchMode("findingCollection", FetchMode.JOIN);
    crit.setFetchMode("findingCollection.datumCollection", FetchMode.JOIN);
    crit.setFetchMode("findingCollection.datumCollection.conditionCollection", FetchMode.JOIN);
    crit.setFetchMode("findingCollection.fileCollection", FetchMode.JOIN);
    crit.setFetchMode("findingCollection.fileCollection.keywordCollection", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List results = appService.query(crit);

    for (int i = 0; i < results.size(); i++) {
        Characterization achar = (Characterization) results.get(i);
        if (springSecurityAclService.currentUserHasReadPermission(achar.getId(),
                SecureClassesEnum.CHAR.getClazz())
                || springSecurityAclService.currentUserHasWritePermission(achar.getId(),
                        SecureClassesEnum.CHAR.getClazz())) {
            checkAssociatedVisibility(achar);
            chars.add(achar);
        } else {
            logger.debug("User doesn't have access ot characterization with id " + achar.getId());
        }
    }
    return chars;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.CompositionServiceHelper.java

License:BSD License

public SampleComposition findCompositionBySampleId(String sampleId) throws Exception {
    if (!springSecurityAclService.currentUserHasReadPermission(Long.valueOf(sampleId),
            SecureClassesEnum.SAMPLE.getClazz())
            && !springSecurityAclService.currentUserHasWritePermission(Long.valueOf(sampleId),
                    SecureClassesEnum.SAMPLE.getClazz())) {
        new NoAccessException("User has no access to the sample " + sampleId);
    }/*  w  w w . jav  a  2  s  .c  om*/
    SampleComposition composition = null;

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    DetachedCriteria crit = DetachedCriteria.forClass(SampleComposition.class);
    crit.createAlias("sample", "sample");
    crit.add(Property.forName("sample.id").eq(new Long(sampleId)));
    crit.setFetchMode("nanomaterialEntityCollection", FetchMode.JOIN);
    crit.setFetchMode("nanomaterialEntityCollection.fileCollection", FetchMode.JOIN);
    crit.setFetchMode("nanomaterialEntityCollection.fileCollection.keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("nanomaterialEntityCollection.composingElementCollection", FetchMode.JOIN);
    crit.setFetchMode("nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection",
            FetchMode.JOIN);
    crit.setFetchMode(
            "nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection.targetCollection",
            FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection", FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection.fileCollection", FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection.fileCollection.keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection.functionCollection", FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection.functionCollection.targetCollection", FetchMode.JOIN);
    crit.setFetchMode("functionalizingEntityCollection.activationMethod", FetchMode.JOIN);
    crit.setFetchMode("chemicalAssociationCollection", FetchMode.JOIN);
    crit.setFetchMode("chemicalAssociationCollection.fileCollection", FetchMode.JOIN);
    crit.setFetchMode("chemicalAssociationCollection.fileCollection.keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("chemicalAssociationCollection.associatedElementA", FetchMode.JOIN);
    crit.setFetchMode("chemicalAssociationCollection.associatedElementB", FetchMode.JOIN);
    crit.setFetchMode("fileCollection", FetchMode.JOIN);
    crit.setFetchMode("fileCollection.keywordCollection", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List result = appService.query(crit);

    if (!result.isEmpty()) {
        composition = (SampleComposition) result.get(0);
        /*if (!springSecurityAclService.currentUserHasReadPermission(composition.getId(), SecureClassesEnum.COMPOSITION.getClazz()) &&
           !springSecurityAclService.currentUserHasWritePermission(composition.getId(), SecureClassesEnum.COMPOSITION.getClazz())) {
           throw new NoAccessException("User doesn't have access to the composition " + composition.getId());
        }*/
    }
    return composition;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public List<String> findSampleIdsBy(String sampleName, String samplePointOfContact,
        String[] nanomaterialEntityClassNames, String[] otherNanomaterialEntityTypes,
        String[] functionalizingEntityClassNames, String[] otherFunctionalizingEntityTypes,
        String[] functionClassNames, String[] otherFunctionTypes, String[] characterizationClassNames,
        String[] otherCharacterizationTypes, String[] wordList) throws Exception {
    List<String> sampleIds = new ArrayList<String>();

    //logger.error("Processing: " + sampleName);

    // can't query for the entire Sample object due to
    // limitations in pagination in SDK

    // added createdDate and sample name in the results so data can be
    // sorted by date and name
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
            .setProjection(Projections.projectionList().add(Projections.property("id"))
                    .add(Projections.property("name")).add(Projections.property("createdDate")));
    if (!StringUtils.isEmpty(sampleName)) {
        TextMatchMode nameMatchMode = new TextMatchMode(sampleName);
        crit.add(Restrictions.ilike("name", nameMatchMode.getUpdatedText(), nameMatchMode.getMatchMode()));
    }//from   ww  w  . j  a v a  2  s .c o  m
    if (!StringUtils.isEmpty(samplePointOfContact)) {
        TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("primaryPointOfContact", "pointOfContact");
        crit.createAlias("pointOfContact.organization", "organization");
        crit.createAlias("otherPointOfContactCollection", "otherPoc", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("otherPoc.organization", "otherOrg", CriteriaSpecification.LEFT_JOIN);
        String[] critStrs = { "pointOfContact.lastName", "pointOfContact.firstName", "pointOfContact.role",
                "organization.name", "otherPoc.lastName", "otherPoc.firstName", "otherOrg.name" };
        for (String critStr : critStrs) {
            Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode.getUpdatedText(),
                    pocMatchMode.getMatchMode());
            disjunction.add(pocCrit);
        }
        crit.add(disjunction);
    }

    // join composition
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0
            || functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
        crit.createAlias("sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
    }
    // join nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // join functionalizing entity
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0) {
            Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class", nanomaterialEntityClassNames);
            disjunction.add(nanoEntityCrit);
        }
        if (otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0) {
            Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class", "OtherNanomaterialEntity");
            Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type", otherNanomaterialEntityTypes);
            Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1, otherNanoCrit2);
            disjunction.add(otherNanoCrit);
        }
        crit.add(disjunction);
    }

    // functionalizing entity
    // need to turn class names into integers in order for the .class
    // clause to work
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0) {
            Integer[] functionalizingEntityClassNameIntegers = this
                    .convertToFunctionalizingEntityClassOrderNumber(functionalizingEntityClassNames);
            Criterion funcEntityCrit = Restrictions.in("funcEntity.class",
                    functionalizingEntityClassNameIntegers);
            disjunction.add(funcEntityCrit);
        }
        if (otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
            Integer classOrderNumber = Constants.FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP
                    .get("OtherFunctionalizingEntity");
            Criterion otherFuncCrit1 = Restrictions.eq("funcEntity.class", classOrderNumber);
            Criterion otherFuncCrit2 = Restrictions.in("funcEntity.type", otherFunctionalizingEntityTypes);
            Criterion otherFuncCrit = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
            disjunction.add(otherFuncCrit);
        }
        crit.add(disjunction);
    }

    // function
    if (functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("nanoEntity.composingElementCollection", "compElement",
                CriteriaSpecification.LEFT_JOIN).createAlias("compElement.inherentFunctionCollection", "inFunc",
                        CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("funcEntity.functionCollection", "func", CriteriaSpecification.LEFT_JOIN);
        if (functionClassNames != null && functionClassNames.length > 0) {
            Criterion funcCrit1 = Restrictions.in("inFunc.class", functionClassNames);
            Criterion funcCrit2 = Restrictions.in("func.class", functionClassNames);
            disjunction.add(funcCrit1).add(funcCrit2);
        }
        if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
            Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq("inFunc.class", "OtherFunction"),
                    Restrictions.in("inFunc.type", otherFunctionTypes));
            Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq("func.class", "OtherFunction"),
                    Restrictions.in("func.type", otherFunctionTypes));
            disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
        }
        crit.add(disjunction);
    }

    // join characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0
            || wordList != null && wordList.length > 0) {
        crit.createAlias("characterizationCollection", "chara", CriteriaSpecification.LEFT_JOIN);
    }
    // characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (characterizationClassNames != null && characterizationClassNames.length > 0) {
            Criterion charCrit = Restrictions.in("chara.class", characterizationClassNames);
            disjunction.add(charCrit);
        }
        if (otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
            Criterion otherCharCrit1 = Restrictions.eq("chara.class", "OtherCharacterization");
            Criterion otherCharCrit2 = Restrictions.in("chara.name", otherCharacterizationTypes);
            Criterion otherCharCrit = Restrictions.and(otherCharCrit1, otherCharCrit2);
            disjunction.add(otherCharCrit);
        }
        crit.add(disjunction);
    }
    // join keyword, finding, publication
    if (wordList != null && wordList.length > 0) {
        crit.createAlias("keywordCollection", "keyword1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("chara.findingCollection", "finding", CriteriaSpecification.LEFT_JOIN)
                .createAlias("finding.fileCollection", "charFile", CriteriaSpecification.LEFT_JOIN)
                .createAlias("charFile.keywordCollection", "keyword2", CriteriaSpecification.LEFT_JOIN);
        // publication keywords
        crit.createAlias("publicationCollection", "pub1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("pub1.keywordCollection", "keyword3", CriteriaSpecification.LEFT_JOIN);
    }

    // keyword
    if (wordList != null && wordList.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        for (String keyword : wordList) {
            // strip wildcards from either ends of keyword
            keyword = StringUtils.stripWildcards(keyword);
            Criterion keywordCrit1 = Restrictions.ilike("keyword1.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit2 = Restrictions.ilike("keyword2.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit3 = Restrictions.ilike("keyword3.name", keyword, MatchMode.ANYWHERE);
            disjunction.add(keywordCrit1);
            disjunction.add(keywordCrit2);
            disjunction.add(keywordCrit3);
        }
        for (String word : wordList) {
            Criterion summaryCrit1 = Restrictions.ilike("chara.designMethodsDescription", word,
                    MatchMode.ANYWHERE);
            Criterion summaryCrit2 = Restrictions.ilike("charFile.description", word, MatchMode.ANYWHERE);
            Criterion summaryCrit = Restrictions.or(summaryCrit1, summaryCrit2);
            disjunction.add(summaryCrit);
        }
        crit.add(disjunction);
    }

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();

    List results = appService.query(crit);

    int resSize = results.size();
    /*
     * We will look only though the maximum amount of allowed records to avoid Exceptions
     */
    int maxCount = appService.getMaxRecordsCount();
    Set<Sample> samples = new HashSet<Sample>();
    for (int i = 0; (i < resSize) && (i < maxCount); i++) {
        try {
            /*
             * There is a bug when searching with keyword "tes", where the following line
             * whould trigger a ClassCastException. Reason unknow but suspected to be reaching
             * the last row of a dataset. 
             */
            //            Object[] row = (Object[]) obj;
            Object[] row = (Object[]) results.get(i);

            Long sampleId = (Long) row[0];
            if (springSecurityAclService.currentUserHasReadPermission(sampleId,
                    SecureClassesEnum.SAMPLE.getClazz())
                    || springSecurityAclService.currentUserHasWritePermission(sampleId,
                            SecureClassesEnum.SAMPLE.getClazz())) {
                Sample sample = new Sample();
                sample.setId(sampleId);
                sample.setName((String) row[1]);
                sample.setCreatedDate((Date) row[2]);
                samples.add(sample);
            } else {
                logger.debug("User doesn't have access to sample of ID: " + sampleId);
            }

        } catch (ClassCastException e) {
            logger.error("Got ClassCastException: " + e.getMessage());
            break;
        }
    }

    List<Sample> orderedSamples = new ArrayList<Sample>(samples);
    // Collections.sort(orderedSamples,
    // Collections.reverseOrder(new Comparators.SampleDateComparator()));

    Collections.sort(orderedSamples, new Comparators.SampleDateComparator());

    for (Sample sample : orderedSamples) {
        sampleIds.add(sample.getId().toString());
    }

    return sampleIds;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public PointOfContact findPointOfContactByNameAndOrg(String firstName, String lastName, String orgName)
        throws Exception {
    PointOfContact poc = null;/*  www  .  j  av a2  s.  co m*/

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
    crit.createAlias("organization", "organization");
    if (!StringUtils.isEmpty(lastName))
        crit.add(Restrictions.eq("lastName", lastName));
    if (!StringUtils.isEmpty(firstName))
        crit.add(Restrictions.eq("firstName", firstName));
    if (!StringUtils.isEmpty(orgName))
        crit.add(Restrictions.eq("organization.name", orgName));
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    List results = appService.query(crit);
    for (int i = 0; i < results.size(); i++) {
        poc = (PointOfContact) results.get(i);
    }
    return poc;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public List<Sample> findSamplesBy(String sampleName, String samplePointOfContact,
        String[] nanomaterialEntityClassNames, String[] otherNanomaterialEntityTypes,
        String[] functionalizingEntityClassNames, String[] otherFunctionalizingEntityTypes,
        String[] functionClassNames, String[] otherFunctionTypes, String[] characterizationClassNames,
        String[] otherCharacterizationTypes, String[] wordList) throws Exception {
    List<String> sampleIds = new ArrayList<String>();

    //logger.error("Processing: " + sampleName);

    // can't query for the entire Sample object due to
    // limitations in pagination in SDK

    // added createdDate and sample name in the results so data can be
    // sorted by date and name
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class);
    //            .setProjection(
    //                  Projections.projectionList()
    //                        .add(Projections.property("id"))
    //                        .add(Projections.property("name"))
    //                        .add(Projections.property("createdDate")));
    if (!StringUtils.isEmpty(sampleName)) {
        TextMatchMode nameMatchMode = new TextMatchMode(sampleName);
        crit.add(Restrictions.ilike("name", nameMatchMode.getUpdatedText(), nameMatchMode.getMatchMode()));
    }// w w w.  jav  a 2 s  .co m
    if (!StringUtils.isEmpty(samplePointOfContact)) {
        TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("primaryPointOfContact", "pointOfContact");
        crit.createAlias("pointOfContact.organization", "organization");
        crit.createAlias("otherPointOfContactCollection", "otherPoc", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("otherPoc.organization", "otherOrg", CriteriaSpecification.LEFT_JOIN);
        String[] critStrs = { "pointOfContact.lastName", "pointOfContact.firstName", "pointOfContact.role",
                "organization.name", "otherPoc.lastName", "otherPoc.firstName", "otherOrg.name" };
        for (String critStr : critStrs) {
            Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode.getUpdatedText(),
                    pocMatchMode.getMatchMode());
            disjunction.add(pocCrit);
        }
        crit.add(disjunction);
    }

    // join composition
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0
            || functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
        crit.createAlias("sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
    }
    // join nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // join functionalizing entity
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0) {
            Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class", nanomaterialEntityClassNames);
            disjunction.add(nanoEntityCrit);
        }
        if (otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0) {
            Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class", "OtherNanomaterialEntity");
            Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type", otherNanomaterialEntityTypes);
            Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1, otherNanoCrit2);
            disjunction.add(otherNanoCrit);
        }
        crit.add(disjunction);
    }

    // functionalizing entity
    // need to turn class names into integers in order for the .class
    // clause to work
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0) {
            Integer[] functionalizingEntityClassNameIntegers = this
                    .convertToFunctionalizingEntityClassOrderNumber(functionalizingEntityClassNames);
            Criterion funcEntityCrit = Restrictions.in("funcEntity.class",
                    functionalizingEntityClassNameIntegers);
            disjunction.add(funcEntityCrit);
        }
        if (otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
            Integer classOrderNumber = Constants.FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP
                    .get("OtherFunctionalizingEntity");
            Criterion otherFuncCrit1 = Restrictions.eq("funcEntity.class", classOrderNumber);
            Criterion otherFuncCrit2 = Restrictions.in("funcEntity.type", otherFunctionalizingEntityTypes);
            Criterion otherFuncCrit = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
            disjunction.add(otherFuncCrit);
        }
        crit.add(disjunction);
    }

    // function
    if (functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("nanoEntity.composingElementCollection", "compElement",
                CriteriaSpecification.LEFT_JOIN).createAlias("compElement.inherentFunctionCollection", "inFunc",
                        CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("funcEntity.functionCollection", "func", CriteriaSpecification.LEFT_JOIN);
        if (functionClassNames != null && functionClassNames.length > 0) {
            Criterion funcCrit1 = Restrictions.in("inFunc.class", functionClassNames);
            Criterion funcCrit2 = Restrictions.in("func.class", functionClassNames);
            disjunction.add(funcCrit1).add(funcCrit2);
        }
        if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
            Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq("inFunc.class", "OtherFunction"),
                    Restrictions.in("inFunc.type", otherFunctionTypes));
            Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq("func.class", "OtherFunction"),
                    Restrictions.in("func.type", otherFunctionTypes));
            disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
        }
        crit.add(disjunction);
    }

    // join characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0
            || wordList != null && wordList.length > 0) {
        crit.createAlias("characterizationCollection", "chara", CriteriaSpecification.LEFT_JOIN);
    }
    // characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (characterizationClassNames != null && characterizationClassNames.length > 0) {
            Criterion charCrit = Restrictions.in("chara.class", characterizationClassNames);
            disjunction.add(charCrit);
        }
        if (otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
            Criterion otherCharCrit1 = Restrictions.eq("chara.class", "OtherCharacterization");
            Criterion otherCharCrit2 = Restrictions.in("chara.name", otherCharacterizationTypes);
            Criterion otherCharCrit = Restrictions.and(otherCharCrit1, otherCharCrit2);
            disjunction.add(otherCharCrit);
        }
        crit.add(disjunction);
    }
    // join keyword, finding, publication
    if (wordList != null && wordList.length > 0) {
        crit.createAlias("keywordCollection", "keyword1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("chara.findingCollection", "finding", CriteriaSpecification.LEFT_JOIN)
                .createAlias("finding.fileCollection", "charFile", CriteriaSpecification.LEFT_JOIN)
                .createAlias("charFile.keywordCollection", "keyword2", CriteriaSpecification.LEFT_JOIN);
        // publication keywords
        crit.createAlias("publicationCollection", "pub1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("pub1.keywordCollection", "keyword3", CriteriaSpecification.LEFT_JOIN);
    }

    // keyword
    if (wordList != null && wordList.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        for (String keyword : wordList) {
            // strip wildcards from either ends of keyword
            keyword = StringUtils.stripWildcards(keyword);
            Criterion keywordCrit1 = Restrictions.ilike("keyword1.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit2 = Restrictions.ilike("keyword2.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit3 = Restrictions.ilike("keyword3.name", keyword, MatchMode.ANYWHERE);
            disjunction.add(keywordCrit1);
            disjunction.add(keywordCrit2);
            disjunction.add(keywordCrit3);
        }
        for (String word : wordList) {
            Criterion summaryCrit1 = Restrictions.ilike("chara.designMethodsDescription", word,
                    MatchMode.ANYWHERE);
            Criterion summaryCrit2 = Restrictions.ilike("charFile.description", word, MatchMode.ANYWHERE);
            Criterion summaryCrit = Restrictions.or(summaryCrit1, summaryCrit2);
            disjunction.add(summaryCrit);
        }
        crit.add(disjunction);
    }

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();

    List results = appService.query(crit);
    List<Sample> samples = new ArrayList<Sample>();
    //      List<String> accessibleData = getAccessibleData();
    for (int i = 0; i < results.size(); i++) {

        try {
            Sample sample = (Sample) results.get(i);
            System.out.println("sample ID test === " + sample.getId());
            samples.add(sample);
        } catch (ClassCastException e) {
            logger.error("Got ClassCastException: " + e.getMessage());
            break;
        }
    }

    List<Sample> orderedSamples = new ArrayList<Sample>(samples);
    // Collections.sort(orderedSamples,
    // Collections.reverseOrder(new Comparators.SampleDateComparator()));

    Collections.sort(orderedSamples, new Comparators.SampleDateComparator());

    for (Sample sample : orderedSamples) {
        sampleIds.add(sample.getId().toString());
    }

    return samples;
}

From source file:gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl.java

License:BSD License

public void updatePOCAssociatedWithCharacterizations(String sampleName, Long oldPOCId, Long newPOCId)
        throws SampleException {
    try {/*  ww w .j  a v  a2s .co  m*/
        CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
                .getApplicationService();
        DetachedCriteria crit = DetachedCriteria.forClass(Characterization.class);
        crit.createAlias("sample", "sample");
        crit.createAlias("pointOfContact", "poc");
        crit.add(Property.forName("poc.id").eq(oldPOCId));
        crit.add(Property.forName("sample.name").eq(sampleName));
        crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List results = appService.query(crit);
        for (int i = 0; i < results.size(); i++) {
            Characterization achar = (Characterization) results.get(i);
            // update POC to the new ID
            achar.getPointOfContact().setId(newPOCId);
            appService.saveOrUpdate(achar);
        }
    } catch (Exception e) {
        String err = "Error in updating POC associated sample characterizations " + sampleName + ". "
                + e.getMessage();
        logger.error(err, e);
        throw new SampleException(err, e);
    }
}

From source file:gr.abiss.calipso.domain.ColumnHeading.java

License:Open Source License

/**
 * this routine is a massive if-then construct that acts as a factory for
 * the right implementation of the responsibilities defined in the
 * "Processor" class (above) based on the type of ColumnHeading - the right
 * implementation will be returned. having everything in one place below,
 * makes it easy to maintain, as the logic of each of the methods are
 * closely interdependent for a given column type for e.g. the kind of
 * hibernate criteria needed depends on what is made available on the UI
 *//*from   w w  w .j a va 2  s. c  om*/
private Processor getProcessor() {
    if (isField()) {
        switch (field.getName().getType()) {
        // ==============================================================

        case 1:
        case 2:
        case 3:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    final Fragment fragment = new Fragment("fragParent", "multiSelect", container);
                    //final Map<String, String> options = field.getOptions();
                    List<CustomAttributeLookupValue> lookupValues = calipsoService.findLookupValues(space,
                            field.getName().getText());
                    // TODO: create a leaf-node only finder method in calipso service
                    List<CustomAttributeLookupValue> leafLookupValues = new LinkedList<CustomAttributeLookupValue>();

                    // leaf selection only for now
                    for (CustomAttributeLookupValue val : lookupValues) {
                        if (CollectionUtils.isEmpty(val.getChildren())) {
                            leafLookupValues.add(val);
                        }
                    }
                    lookupValues = null;

                    final CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values", leafLookupValues,
                            new IChoiceRenderer<CustomAttributeLookupValue>() {

                                @Override
                                public Object getDisplayValue(CustomAttributeLookupValue object) {
                                    return fragment.getString(object.getNameTranslationResourceKey());
                                }

                                @Override
                                public String getIdValue(CustomAttributeLookupValue object, int index) {
                                    return object.getId() + "";
                                }
                            });
                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValueList()) {
                        List values = filterCriteria.getValues();
                        List<Integer> keys = new ArrayList<Integer>(values.size());
                        for (Object o : values) {
                            if (o instanceof CustomAttributeLookupValue) {
                                CustomAttributeLookupValue val = (CustomAttributeLookupValue) o;
                                keys.add(NumberUtils.createInteger(val.getId() + ""));
                            } else {
                                keys.add(NumberUtils.createInteger(o + ""));
                            }
                        }
                        criteria.add(Restrictions.in(getNameText(), keys));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValueList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueListFromQueryString(s);
                }
            };
        // ==============================================================
        case 4: // decimal number
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(EQ, NOT_EQ, GT, LT, BETWEEN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "textField", container);
                    TextField textField = new TextField("value", Double.class);
                    textField.setModel(new PropertyModel(filterCriteria, "value"));
                    fragment.add(textField);
                    if (filterCriteria.getExpression() == BETWEEN) {
                        TextField textField2 = new TextField("value2", Double.class);
                        textField2.setModel(new PropertyModel(filterCriteria, "value2"));
                        fragment.add(textField2);
                    } else {
                        fragment.add(new WebMarkupContainer("value2").setVisible(false));
                    }
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        Object value = filterCriteria.getValue();
                        switch (filterCriteria.getExpression()) {
                        case EQ:
                            criteria.add(Restrictions.eq(getNameText(), value));
                            break;
                        case NOT_EQ:
                            criteria.add(Restrictions.not(Restrictions.eq(name.text, value)));
                            break;
                        case GT:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            break;
                        case LT:
                            criteria.add(Restrictions.lt(getNameText(), value));
                            break;
                        case BETWEEN:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            criteria.add(Restrictions.lt(getNameText(), filterCriteria.getValue2()));
                            break;
                        default:
                        }
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(Double.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, Double.class);
                }

            };
        // ==============================================================
        case 6: // date
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(EQ, NOT_EQ, GT, LT, BETWEEN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "dateField", container);
                    DateField calendar = new DateField("value",
                            new PropertyModel(filterCriteria, "value")/*,
                                                                      false*/);
                    fragment.add(calendar);
                    if (filterCriteria.getExpression() == BETWEEN) {
                        DateField calendar2 = new DateField("value2",
                                new PropertyModel(filterCriteria, "value2")/*,
                                                                           false*/);
                        fragment.add(calendar2);
                    } else {
                        fragment.add(new WebMarkupContainer("value2").setVisible(false));
                    }
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        Object value = filterCriteria.getValue();
                        switch (filterCriteria.getExpression()) {
                        case EQ:
                            criteria.add(Restrictions.eq(getNameText(), value));
                            break;
                        case NOT_EQ:
                            criteria.add(Restrictions.not(Restrictions.eq(getNameText(), value)));
                            break;
                        case GT:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            break;
                        case LT:
                            criteria.add(Restrictions.lt(getNameText(), value));
                            break;
                        case BETWEEN:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            criteria.add(Restrictions.lt(getNameText(), filterCriteria.getValue2()));
                            break;
                        default:
                        }
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(Date.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, Date.class);
                }
            };
        // ==============================================================
        case 5: // free text
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        // TODO:
        case 10:// organization
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        // TODO:
        case 11:// file
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        case 200:// attachment
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        case 20:// is user
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };

        case 25:// is user
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        case 100: // Assignable spaces (move to space)
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "multiSelect", container);
                    final Map<String, String> options = field.getOptions();
                    List<String> keys = null;
                    if (options != null) {
                        keys = new ArrayList(options.keySet()); // bound
                        // value
                    } else {
                        keys = new ArrayList();
                    }

                    List<Space> spaces = new LinkedList<Space>();
                    for (String key : keys) {
                        // spaces.add(ComponentUtils.getJtrac(c).loadSpace(Long.parseLong(key)));
                        spaces.add(calipsoService.loadSpace(Long.parseLong(key)));
                    } // for
                    CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values", spaces,
                            new IChoiceRenderer<Space>() {
                                private static final long serialVersionUID = 1L;

                                @Override
                                public Object getDisplayValue(Space o) {
                                    logger.info("Option for space: " + o);
                                    String name = o.getName();
                                    return name != null ? name : o.getId();
                                }

                                @Override
                                public String getIdValue(Space o, int index) {
                                    return o.getId() + "";
                                }
                            });

                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValueList()) {
                        List values = filterCriteria.getValues();
                        criteria.add(Restrictions.in(getNameText(), values));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValueList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueListFromQueryString(s);
                }
            };
        // ==============================================================
        default:
            throw new RuntimeException("Unknown Column Heading " + name);
        }
    } else { // this is not a custom field but one of the "built-in" columns
        switch (name) {
        // ==============================================================
        case ID:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(EQ);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        // should never come here for criteria: see
                        // ItemSearch#getRefId()
                        throw new RuntimeException("should not come here for 'id'");
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        // ==============================================================
        case SUMMARY:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        criteria.add(Restrictions.ilike(getNameText(), (String) filterCriteria.getValue(),
                                MatchMode.ANYWHERE));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };
        // ==============================================================
        case DETAIL:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(CONTAINS);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    return getTextFieldFragment(container);
                }

                void addRestrictions(DetachedCriteria criteria) {
                    // do nothing, 'detail' already processed, see:
                    // ItemSearch#getSearchText()
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(String.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, String.class);
                }
            };

        // ==============================================================
        case STATUS:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "multiSelect", container);
                    // status selectable only when context space is not null
                    // final Map<Integer, String> options =
                    // space.getMetadata().getStatesMap();
                    final Map<Integer, String> options;
                    if (space == null) {
                        options = State.getSpecialStates();
                    } else {
                        options = space.getMetadata().getStatesMap();
                    }
                    options.remove(State.NEW);
                    CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values",
                            new ArrayList(options.keySet()), new IChoiceRenderer() {
                                public Object getDisplayValue(Object o) {
                                    return options.get(o);
                                }

                                public String getIdValue(Object o, int i) {
                                    return o.toString();
                                }
                            });
                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValueList()) {
                        criteria.add(Restrictions.in(getNameText(), filterCriteria.getValues()));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValueList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    //logger.info("loadFromQueryString: "+s);
                    setStatusListFromQueryString(s);
                }
            };
        // ==============================================================
        case ASSIGNED_TO:
        case LOGGED_BY:
        case REPORTED_BY:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN, IS_NULL);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "multiSelect", container);
                    List<User> users = null;
                    if (space == null) {
                        users = calipsoService.findUsersForUser(user);
                    } else {
                        users = calipsoService.findUsersForSpace(space.getId());
                    }
                    CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values", users,
                            new IChoiceRenderer() {
                                public Object getDisplayValue(Object o) {
                                    return ((User) o).getFullName();
                                }

                                public String getIdValue(Object o, int i) {
                                    return ((User) o).getId() + "";
                                }
                            });
                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValueList()) {
                        criteria.add(Restrictions.in(getNameText(), filterCriteria.getValues()));
                    } else if (filterIsNullExpression()) {
                        criteria.add(Restrictions.isNull(getNameText()));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromUserList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setUserListFromQueryString(s, calipsoService);
                }
            };
        // ==============================================================

        case ASSET_TYPE:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "multiSelect", container);

                    List<AssetType> assetTypes = calipsoService.findAllAssetTypes();
                    CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values", assetTypes,
                            new IChoiceRenderer() {
                                public Object getDisplayValue(Object o) {
                                    return ((AssetType) o).getName();
                                }

                                public String getIdValue(Object o, int i) {
                                    return String.valueOf(((AssetType) o).getId());
                                }
                            });
                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));

                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValueList()) {
                        criteria.createAlias("assets", "assets");
                        criteria.add(Restrictions.in("assets.assetType", filterCriteria.getValues()));
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromAssetTypeList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setAssetTypeListFromQueryString(s, user, calipsoService);
                }
            };
        // ==============================================================
        case TIME_STAMP:
        case DUE_TO:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(BETWEEN, GT, LT, EQ, NOT_EQ);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "dateField", container);
                    DateField calendar = new DateField("value",
                            new PropertyModel(filterCriteria, "value")/*,
                                                                      false*/);
                    fragment.add(calendar);
                    if (filterCriteria.getExpression() == BETWEEN) {
                        DateField calendar2 = new DateField("value2",
                                new PropertyModel(filterCriteria, "value2")/*,
                                                                           false*/);
                        fragment.add(calendar2);
                    } else {
                        fragment.add(new WebMarkupContainer("value2").setVisible(false));
                    }
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        Object value = filterCriteria.getValue();
                        switch (filterCriteria.getExpression()) {
                        case EQ:
                            criteria.add(Restrictions.eq(getNameText(), value));
                            break;
                        case NOT_EQ:
                            criteria.add(Restrictions.not(Restrictions.eq(getNameText(), value)));
                            break;
                        case GT:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            break;
                        case LT:
                            criteria.add(Restrictions.lt(getNameText(), value));
                            break;
                        case BETWEEN:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            criteria.add(Restrictions.lt(getNameText(), filterCriteria.getValue2()));
                            break;
                        default:
                        }
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(Date.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, Date.class);
                }
            };
        // ==============================================================
        case SPACE:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(IN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "multiSelect", container);
                    List<Space> spaces = new ArrayList(user.getSpaces());
                    CheckBoxMultipleChoice choice = new CheckBoxMultipleChoice("values", spaces,
                            new IChoiceRenderer() {
                                public Object getDisplayValue(Object o) {
                                    return ((Space) o).getName();
                                }

                                public String getIdValue(Object o, int i) {
                                    return ((Space) o).getId() + "";
                                }
                            });
                    fragment.add(choice);
                    choice.setModel(new PropertyModel(filterCriteria, "values"));
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    // already handled space as special case, see
                    // ItemSearch#getSelectedSpaces()
                }

                String getAsQueryString() {
                    return getQueryStringFromSpaceList();
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setSpaceListFromQueryString(s, user, calipsoService);
                }
            };

        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        case TOTAL_RESPONSE_TIME:
        case TIME_FROM_CREATION_TO_FIRST_REPLY:
        case TIME_FROM_CREATION_TO_CLOSE:
            return new ProcessorCustom() {
                private Class validationClass = null;

                List<Expression> getValidFilterExpressions() {
                    return getAsList(BETWEEN, GT, LT);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "effortField", container);
                    WebMarkupContainer days = new WebMarkupContainer("days");

                    if (name.equals(TOTAL_RESPONSE_TIME)) {
                        validationClass = Double.class;
                    } else {
                        validationClass = Long.class;
                    }

                    TextField textField = new TextField("value", validationClass);
                    days.add(textField);
                    // textField.setModel(new PropertyModel(this,
                    // "filterCriteria.value"));
                    textField.setModel(new PropertyModel(filterCriteria, "value"));
                    fragment.add(days);

                    WebMarkupContainer days2 = new WebMarkupContainer("days2");
                    if (filterCriteria.getExpression() == BETWEEN) {
                        TextField textField2 = new TextField("value2", validationClass);
                        days2.add(textField2);
                        // textField2.setModel(new PropertyModel(this,
                        // "filterCriteria.value2"));
                        textField2.setModel(new PropertyModel(filterCriteria, "value2"));
                    } // if
                    else {
                        fragment.add(new WebMarkupContainer("value2").setVisible(false));
                        days2.setVisible(false);
                    } // else
                    fragment.add(days2);
                    // fragment.setVisible(isVisible());
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                }

                void addRestrictions(CustomCriteria customCriteria) {
                    if (filterHasValue()) {
                        String criteriaObjectClass = null;
                        if (validationClass != null) {
                            criteriaObjectClass = validationClass.getCanonicalName();
                        } // if

                        Object value = filterCriteria.getValue();
                        Object value2 = filterCriteria.getValue2();

                        Double v1 = new Double(value.toString());
                        value = v1 * 86400;// In Seconds
                        switch (filterCriteria.getExpression()) {
                        case GT:
                            customCriteria.add(name.getText(), CustomCriteria.GT, value.toString(),
                                    criteriaObjectClass);
                            break;
                        case LT:
                            customCriteria.add(name.getText(), CustomCriteria.LT, value.toString(),
                                    criteriaObjectClass);
                            break;
                        case BETWEEN:
                            Double v2 = new Double(value2.toString());
                            value2 = v2 * 86400; // In Seconds
                            customCriteria.add(name.getText(), CustomCriteria.GET, value.toString(),
                                    criteriaObjectClass);
                            customCriteria.add(name.getText(), CustomCriteria.LET, value2.toString(),
                                    criteriaObjectClass);
                            break;
                        default:
                        }
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(Long.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, Long.class);
                }
            };

        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        case PLANNED_EFFORT:
            return new Processor() {
                List<Expression> getValidFilterExpressions() {
                    return getAsList(EQ, NOT_EQ, GT, LT, BETWEEN);
                }

                Fragment getFilterUiFragment(MarkupContainer container, User user, Space space,
                        CalipsoService calipsoService) {
                    Fragment fragment = new Fragment("fragParent", "effortField2", container);
                    EffortField effortField = new EffortField("value",
                            new PropertyModel(filterCriteria, "value"), false);
                    fragment.add(effortField);
                    if (filterCriteria.getExpression() == BETWEEN) {
                        EffortField effortField2 = new EffortField("value2",
                                new PropertyModel(filterCriteria, "value2"), false);
                        fragment.add(new WebMarkupContainer("and"));
                        fragment.add(effortField2);
                    } else {
                        fragment.add(new WebMarkupContainer("and").setVisible(false));
                        fragment.add(new WebMarkupContainer("value2").setVisible(false));
                    }
                    return fragment;
                }

                void addRestrictions(DetachedCriteria criteria) {
                    if (filterHasValue()) {
                        Object value = filterCriteria.getValue();
                        switch (filterCriteria.getExpression()) {
                        case EQ:
                            criteria.add(Restrictions.eq(getNameText(), value));
                            break;
                        case NOT_EQ:
                            criteria.add(Restrictions.not(Restrictions.eq(getNameText(), value)));
                            break;
                        case GT:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            break;
                        case LT:
                            criteria.add(Restrictions.lt(getNameText(), value));
                            break;
                        case BETWEEN:
                            criteria.add(Restrictions.gt(getNameText(), value));
                            criteria.add(Restrictions.lt(getNameText(), filterCriteria.getValue2()));
                            break;
                        default:
                        }
                    }
                }

                String getAsQueryString() {
                    return getQueryStringFromValue(Integer.class);
                }

                void loadFromQueryString(String s, User user, CalipsoService calipsoService) {
                    setValueFromQueryString(s, Integer.class);
                }
            };

        // ==============================================================
        default:
            throw new RuntimeException("Unknown Column Heading " + name);
        }
    }
}

From source file:id.ac.idu.backend.dao.impl.CustomerDAOImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w  w  w .  ja v  a2  s. c  om*/
public Customer getCustomerByOrder(id.ac.idu.backend.model.Order order) {
    DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);

    criteria.createAlias("orders", "au");
    criteria.add(Restrictions.eq("au.id", Long.valueOf(order.getId())));

    return (Customer) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));
}