org.openmrs.Concept

Here are the examples of the java api org.openmrs.Concept taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

153 Examples 7

19 Source : ConceptsCsvParser.java
with MIT License
from mekomsolutions

@Override
public Concept save(Concept instance) {
    return conceptService.saveConcept(instance);
}

19 Source : ConceptComplexLineProcessor.java
with MIT License
from mekomsolutions

public Concept fill(Concept instance, CsvLine line) throws IllegalArgumentException {
    if (!DATATYPE_COMPLEX.equals(line.get(ConceptLineProcessor.HEADER_DATATYPE))) {
        return instance;
    }
    ConceptComplex cc = new ConceptComplex(instance);
    if (instance.getId() != null) {
        // below overrides any other processors work, so this one should be called first
        cc = conceptService.getConceptComplex(instance.getId());
    }
    cc.setDatatype(conceptService.getConceptDatatypeByName(DATATYPE_COMPLEX));
    cc.setHandler(line.getString(HEADER_HANDLER));
    return cc;
}

19 Source : ConceptAnswersEditorTest.java
with Apache License 2.0
from isstac

/**
 * @see ConceptAnswersEditor#setAsText(String)
 */
@Test
public void setAsText_shouldSetTheSortWeightsWithTheLeastPossibleChanges() {
    ConceptService service = Context.getConceptService();
    Concept c = service.getConcept(21);
    ConceptAnswersEditor editor = new ConceptAnswersEditor(c.getAnswers(true));
    editor.setAsText("22 7 8");
    // conceptId=7
    ConceptAnswer ca1 = service.getConceptAnswer(1);
    // conceptId=8
    ConceptAnswer ca2 = service.getConceptAnswer(2);
    // conceptId=22
    ConceptAnswer ca3 = service.getConceptAnswer(3);
    Concept cafter = service.getConcept(21);
    replacedert.replacedertEquals(3, cafter.getAnswers(true).size());
    replacedert.replacedertTrue(ca3.getSortWeight() < ca1.getSortWeight());
    replacedert.replacedertTrue(ca1.getSortWeight() < ca2.getSortWeight());
}

19 Source : ProgramEditor.java
with Apache License 2.0
from isstac

/**
 * @should set using concept id
 * @should set using concept uuid
 * @should set using program id
 * @should set using program uuid
 */
@Override
public void setAsText(String text) throws IllegalArgumentException {
    if (StringUtils.hasText(text)) {
        try {
            if (text.startsWith("concept.")) {
                Integer conceptId = Integer.valueOf(text.substring(text.indexOf('.') + 1));
                Concept c = Context.getConceptService().getConcept(conceptId);
                setValue(Context.getProgramWorkflowService().getProgramByName(c.getName().getName()));
            } else {
                Integer programId = Integer.valueOf(text);
                setValue(Context.getProgramWorkflowService().getProgram(programId));
            }
        } catch (Exception ex) {
            Program p;
            if (text.startsWith("concept.")) {
                Concept c = Context.getConceptService().getConceptByUuid(text.substring(text.indexOf('.') + 1));
                p = Context.getProgramWorkflowService().getProgramByName(c.getName().getName());
            } else {
                p = Context.getProgramWorkflowService().getProgramByUuid(text);
            }
            setValue(p);
            if (p == null) {
                log.error("Error setting text: " + text, ex);
                throw new IllegalArgumentException("Program not found: " + text, ex);
            }
        }
    } else {
        setValue(null);
    }
}

19 Source : Result.java
with Apache License 2.0
from isstac

/**
 * A result from the logic service. A result can be 0-to-n date-values pairs. You can treat the
 * result as a list or easily coerce it into a simple value as needed. <br>
 * <br>
 * When possible, results carry references to more complex objects so that code that deals with
 * results and has some prior knowledge of the objects returned by a particular rule can more easily
 * get to the full-featured objects instead of the simplified values in the date-value pairs.<br>
 * <br>
 * TODO: better support/handling of NULL_RESULT
 */
public clreplaced Result extends ArrayList<Result> {

    private static final long serialVersionUID = -5587574403423820797L;

    /**
     * Core datatypes for a result. Each result is one of these datatypes, but can be easily coerced
     * into the other datatypes. To promote flexibility and maximize re-usability of logic rules,
     * the value of a result can be controlled individually for each datatype — i.e., specific
     * datatype representations of a single result can be overridden. For example, a result could
     * have a <em>numeric</em> value of 0.15 and its text value could be overridden to be
     * "15 percent" or "Fifteen percent."
     */
    public enum Datatype {

        /**
         * Represents a true/false type of result
         */
        BOOLEAN,
        /**
         * Represents a Concept type of result
         */
        CODED,
        /**
         * Represents a date type of result
         */
        DATETIME,
        /**
         * Represents number (float, double, int) type of results
         */
        NUMERIC,
        /**
         * Represents string type of results
         */
        TEXT
    }

    private Datatype datatype;

    private Date resultDatetime;

    private Boolean valueBoolean;

    private Concept valueCoded;

    private Date valueDatetime;

    private Double valueNumeric;

    private String valueText;

    private Object resultObject;

    private static final Result emptyResult = new EmptyResult();

    public Result() {
    }

    /**
     * Builds result upon another result — the first step in create a result that contains a
     * list of other results.
     *
     * @param result the result that will be the sole member of the new result
     * @should not fail with null result
     */
    public Result(Result result) {
        if (result != null) {
            this.add(result);
        }
    }

    /**
     * Builds a result from a list of results
     *
     * @param list a list of results
     * @should not fail with null list
     * @should not fail with empty list
     */
    public Result(List<Result> list) {
        if (!(list == null || list.isEmpty())) {
            this.addAll(list);
        }
    }

    /**
     * Builds a boolean result with a result date of today
     *
     * @param valueBoolean
     */
    public Result(Boolean valueBoolean) {
        this(new Date(), valueBoolean, null);
    }

    /**
     * Builds a boolean result with a specific result date
     *
     * @param resultDate
     * @param valueBoolean
     */
    public Result(Date resultDate, Boolean valueBoolean, Object obj) {
        this(resultDate, Datatype.BOOLEAN, valueBoolean, null, null, null, null, obj);
    }

    /**
     * Builds a coded result with a result date of today
     *
     * @param valueCoded
     */
    public Result(Concept valueCoded) {
        this(new Date(), valueCoded, null);
    }

    /**
     * Builds a coded result with a specific result date
     *
     * @param resultDate
     * @param valueCoded
     */
    public Result(Date resultDate, Concept valueCoded, Object obj) {
        this(resultDate, Datatype.CODED, null, valueCoded, null, null, null, obj);
    }

    /**
     * Builds a coded result from an observation
     *
     * @param obs
     */
    public Result(Obs obs) {
        this(obs.getObsDatetime(), null, obs.getValueAsBoolean(), obs.getValueCoded(), obs.getValueDatetime(), obs.getValueNumeric(), obs.getValueText(), obs);
        Concept concept = obs.getConcept();
        ConceptDatatype conceptDatatype;
        if (concept != null) {
            conceptDatatype = concept.getDatatype();
            if (conceptDatatype == null) {
                return;
            }
            if (conceptDatatype.isCoded()) {
                this.datatype = Datatype.CODED;
            } else if (conceptDatatype.isNumeric()) {
                this.datatype = Datatype.NUMERIC;
            } else if (conceptDatatype.isDate()) {
                this.datatype = Datatype.DATETIME;
            } else if (conceptDatatype.isText()) {
                this.datatype = Datatype.TEXT;
            } else if (conceptDatatype.isBoolean()) {
                this.datatype = Datatype.BOOLEAN;
            }
        }
    }

    /**
     * Builds a datetime result with a result date of today
     *
     * @param valueDatetime
     */
    public Result(Date valueDatetime) {
        this(new Date(), valueDatetime, null);
    }

    /**
     * Builds a datetime result with a specific result date
     *
     * @param resultDate
     * @param valueDatetime
     */
    public Result(Date resultDate, Date valueDatetime, Object obj) {
        this(resultDate, Datatype.DATETIME, null, null, valueDatetime, null, null, obj);
    }

    /**
     * Builds a numeric result with a result date of today
     *
     * @param valueNumeric
     */
    public Result(Double valueNumeric) {
        this(new Date(), valueNumeric, null);
    }

    /**
     * Builds a numeric result with a specific result date
     *
     * @param resultDate
     * @param valueNumeric
     */
    public Result(Date resultDate, Double valueNumeric, Object obj) {
        this(resultDate, Datatype.NUMERIC, null, null, null, valueNumeric, null, obj);
    }

    /**
     * Builds a numeric result with a result date of today
     *
     * @param valueNumeric
     */
    public Result(Integer valueNumeric) {
        this(new Date(), valueNumeric, null);
    }

    /**
     * Builds a numeric result with a specific result date
     *
     * @param resultDate
     * @param valueNumeric
     */
    public Result(Date resultDate, Integer valueNumeric, Object obj) {
        this(resultDate, Datatype.NUMERIC, null, null, null, valueNumeric.doubleValue(), null, obj);
    }

    /**
     * Builds a text result with a result date of today
     *
     * @param valueText
     */
    public Result(String valueText) {
        this(new Date(), valueText, null);
    }

    /**
     * Builds a text result with a specific result date
     *
     * @param resultDate
     * @param valueText
     */
    public Result(Date resultDate, String valueText, Object obj) {
        this(resultDate, Datatype.TEXT, null, null, null, null, valueText, obj);
    }

    /**
     * Builds a result date with specific (overloaded) values — i.e., instead of simply
     * accepting the default translation of one datatype into another (e.g., a date translated
     * automatically into string format), this contructor allows the various datatype
     * representations of the result to be individually controlled. Any values set to <em>null</em>
     * will yield the natural translation of the default datatype. For example,
     *
     * <pre>
     * Result result = new Result(new Date(), 2.5);
     * replacedertEqualtes("2.5", result.toString());
     *
     * Result result = new Result(new Date(), Result.Datatype.NUMERIC, 2.5, null, null, "Two and a half", null);
     * replacedertEquals("Two and a half", result.toString());
     * </pre>
     *
     * @param resultDate
     * @param datatype
     * @param valueBoolean
     * @param valueCoded
     * @param valueDatetime
     * @param valueNumeric
     * @param valueText
     * @param object
     */
    public Result(Date resultDate, Datatype datatype, Boolean valueBoolean, Concept valueCoded, Date valueDatetime, Double valueNumeric, String valueText, Object object) {
        this.resultDatetime = resultDate;
        this.valueNumeric = valueNumeric;
        this.valueDatetime = valueDatetime;
        this.valueCoded = valueCoded;
        this.valueText = valueText;
        this.valueBoolean = valueBoolean;
        this.datatype = datatype;
        this.resultObject = object;
    }

    /**
     * @return null/empty result
     */
    public static final Result emptyResult() {
        return emptyResult;
    }

    /**
     * Returns the datatype of the result. If the result is a list of other results, then the
     * datatype of the first element is returned
     *
     * @return datatype of the result
     */
    public Datatype getDatatype() {
        if (isSingleResult()) {
            return this.datatype;
        }
        // TODO: better option than defaulting to first element's datatype?
        return this.get(0).getDatatype();
    }

    /**
     * Changes the result date time — not to be confused with a value that is a date. The
     * result date time is typically the datetime that the observation was recorded.
     *
     * @param resultDatetime
     */
    public void setResultDate(Date resultDatetime) {
        this.resultDatetime = resultDatetime;
    }

    /**
     * Changes the default datatype of the result
     *
     * @param datatype
     */
    public void setDatatype(Datatype datatype) {
        this.datatype = datatype;
    }

    /**
     * Overrides the boolean representation of ths result without changing the default datatype
     *
     * @param valueBoolean
     */
    public void setValueBoolean(Boolean valueBoolean) {
        this.valueBoolean = valueBoolean;
    }

    /**
     * Overrides the coded representation of ths result without changing the default datatype
     *
     * @param valueCoded
     */
    public void setValueCoded(Concept valueCoded) {
        this.valueCoded = valueCoded;
    }

    /**
     * Overrides the datetime representation of ths result without changing the default datatype
     *
     * @param valueDatetime
     */
    public void setValueDatetime(Date valueDatetime) {
        this.valueDatetime = valueDatetime;
    }

    /**
     * Overrides the numeric representation of ths result without changing the default datatype
     *
     * @param valueNumeric
     */
    public void setValueNumeric(Integer valueNumeric) {
        this.valueNumeric = valueNumeric.doubleValue();
    }

    /**
     * Overrides the numeric representation of ths result without changing the default datatype
     *
     * @param valueNumeric
     */
    public void setValueNumeric(Double valueNumeric) {
        this.valueNumeric = valueNumeric;
    }

    /**
     * Overrides the text representation of ths result without changing the default datatype
     *
     * @param valueText
     */
    public void setValueText(String valueText) {
        this.valueText = valueText;
    }

    /**
     * Returns the data of the result (not to be confused with a data value). For example, if a
     * result represents an observation like DATE STARTED ON HIV TREATMENT, the <em>result date</em>
     * (returned by this method) would be the date the observation was recorded while the
     * <em>toDatetime()</em> method would be used to get the actual answer (when the patient started
     * their treatment).
     *
     * @return date of the result (usually the date the result was recorded or observed)
     * @see #toDatetime()
     */
    public Date getResultDate() {
        if (isSingleResult()) {
            return resultDatetime;
        }
        return this.get(0).getResultDate();
    }

    /**
     * Get the result object
     *
     * @return the underlying result object
     */
    public Object getResultObject() {
        return this.resultObject;
    }

    /**
     * Set the result object
     *
     * @param object
     */
    public void setResultObject(Object object) {
        this.resultObject = object;
    }

    /**
     * @return boolean representation of the result. For non-boolean results, this will either be
     *         the overridden boolean value (if specifically defined) or a boolean representation of
     *         the default datatype. If the result is a list, then return false only if all members
     *         are false
     *         <table summary="Return logic">
     *         <tr>
     *         <th>Datatype</th>
     *         <th>Returns</th>
     *         </tr>
     *         <tr>
     *         <td>CODED</td>
     *         <td>false for concept FALSE<br>
     *         true for all others</td>
     *         </tr>
     *         <tr>
     *         <td>DATETIME</td>
     *         <td>true for any date value<br>
     *         false if the date is null</td>
     *         </tr>
     *         <tr>
     *         <td>NUMERIC</td>
     *         <td>true for any non-zero number<br>
     *         false for zero</td>
     *         </tr>
     *         <tr>
     *         <td>TEXT</td>
     *         <td>true for any non-blank value<br>
     *         false if blank or null</td>
     *         </tr>
     *         </table>
     */
    public Boolean toBoolean() {
        if (isSingleResult()) {
            if (datatype == null) {
                return valueBoolean;
            }
            switch(datatype) {
                case BOOLEAN:
                    return (valueBoolean == null ? false : valueBoolean);
                case CODED:
                    // TODO: return
                    return (valueCoded != null);
                // false for "FALSE"
                // concept
                case DATETIME:
                    return (valueDatetime != null);
                case NUMERIC:
                    return (valueNumeric != null && valueNumeric != 0);
                case TEXT:
                    return (valueText != null && valueText.length() >= 1);
                default:
                    return valueBoolean;
            }
        }
        for (Result r : this) {
            if (!r.toBoolean()) {
                return false;
            }
        }
        return true;
    }

    /**
     * @return concept for result. For non-concept results, returns the concept value if it was
     *         overridden (specifically defined for the result), otherwise returns <em>null</em>. If
     *         the result is a list, then the concept for the first member is returned.
     */
    public Concept toConcept() {
        if (isSingleResult()) {
            return valueCoded;
        }
        return this.get(0).toConcept();
    }

    /**
     * @return the datetime representation of the result <em>value</em> (not to be confused with the
     *         result's own datetime). For non-datetime results, this will return the overridden
     *         datetime value (if specifically defined) or datetime representation of the default
     *         datatype. If the result is a list, then the datetime representation of the first
     *         member is returned.
     *         <table summary="Return logic">
     *         <tr>
     *         <th>Datatype</th>
     *         <th>Returns</th>
     *         </tr>
     *         <tr>
     *         <td>BOOLEAN</td>
     *         <td>null</td>
     *         </tr>
     *         <tr>
     *         <td>CODED</td>
     *         <td>null</td>
     *         </tr>
     *         <tr>
     *         <td>NUMERIC</td>
     *         <td>null</td>
     *         </tr>
     *         <tr>
     *         <td>TEXT</td>
     *         <td>If the text can be parsed into a date, then that value is returned;<br>
     *         otherwise returns <em>null</em></td>
     *         </tr>
     *         </table>
     */
    public Date toDatetime() {
        if (isSingleResult()) {
            if (valueDatetime != null) {
                return valueDatetime;
            }
            if (datatype == Datatype.TEXT && valueText != null) {
                try {
                    return Context.getDateFormat().parse(valueText);
                } catch (Exception e) {
                }
            }
            return valueDatetime;
        }
        return this.get(0).toDatetime();
    }

    /**
     * @return numeric representation of the result. For non-numeric results, this will either be
     *         the overridden numeric value (if specifically defined) or a numeric representation of
     *         the default datatype. If the result is a list, then the value of the first element is
     *         returned.
     *         <table summary="Return logic">
     *         <tr>
     *         <th>Datatype</th>
     *         <th>Returns</th>
     *         </tr>
     *         <tr>
     *         <td>BOOLEAN</td>
     *         <td>1 for true<br>
     *         0 for false</td>
     *         </tr>
     *         <tr>
     *         <td>CODED</td>
     *         <td>zero (0)</td>
     *         </tr>
     *         <tr>
     *         <tr>
     *         <td>DATETIME</td>
     *         <td>Number of milliseconds since Java's epoch</td>
     *         </tr>
     *         <tr>
     *         <td>TEXT</td>
     *         <td>numeric value of text if it can be parsed into a number<br>
     *         otherwise zero (0)</td> </tr>
     *         </table>
     */
    public Double toNumber() {
        if (isSingleResult()) {
            if (datatype == null) {
                return valueNumeric;
            }
            switch(datatype) {
                case BOOLEAN:
                    return (valueBoolean == null || !valueBoolean ? 0D : 1D);
                case CODED:
                    return 0D;
                case DATETIME:
                    return (valueDatetime == null ? 0 : Long.valueOf(valueDatetime.getTime()).doubleValue());
                case NUMERIC:
                    return (valueNumeric == null ? 0D : valueNumeric);
                case TEXT:
                    try {
                        return Double.parseDouble(valueText);
                    } catch (Exception e) {
                        return 0D;
                    }
                default:
                    return valueNumeric;
            }
        }
        return this.get(0).toNumber();
    }

    /**
     * @return string representation of the result. For non-text results, this will either be the
     *         overridden text value (if specifically defined) or a string representation of the
     *         default datatype value. If the result is a list, then the string representation of
     *         all members a joined with commas.
     */
    @Override
    public String toString() {
        if (isSingleResult()) {
            if (datatype == null) {
                return valueText == null ? "" : valueText;
            }
            switch(datatype) {
                case BOOLEAN:
                    return (valueBoolean ? "true" : "false");
                case CODED:
                    return (valueCoded == null ? "" : valueCoded.getName(Context.getLocale()).getName());
                case DATETIME:
                    return (valueDatetime == null ? "" : Context.getDateFormat().format(valueDatetime));
                case NUMERIC:
                    return (valueNumeric == null ? "" : String.valueOf(valueNumeric));
                case TEXT:
                    return (valueText == null ? "" : valueText);
                default:
                    return valueText;
            }
        }
        StringBuilder s = new StringBuilder();
        for (Result r : this) {
            if (s.length() > 0) {
                s.append(",");
            }
            s.append(r.toString());
        }
        return s.toString();
    }

    /**
     * @return the object replacedociated with the result (generally, this is used internally or for
     *         advanced rule design)
     * @should return resultObject for single results
     * @should return all results for result list
     */
    public Object toObject() {
        if (isSingleResult()) {
            return resultObject;
        }
        if (this.size() == 1) {
            return this.get(0).toObject();
        }
        throw new LogicException("This result represents more than one result, you cannot call toObject on multiple results");
    }

    /**
     * @return true if result is empty
     */
    public boolean isNull() {
        // EmptyResult has its own implementation
        return false;
    // that should return true
    }

    /**
     * @return true if the result has any non-zero, non-empty value
     */
    public boolean exists() {
        if (isSingleResult()) {
            return ((valueBoolean != null && valueBoolean) || valueCoded != null || valueDatetime != null || (valueNumeric != null && valueNumeric != 0) || (valueText != null && valueText.length() > 0));
        }
        for (Result r : this) {
            if (r.exists()) {
                return true;
            }
        }
        return false;
    }

    public boolean contains(Concept concept) {
        return containsConcept(concept.getConceptId());
    }

    /**
     * @return all results greater than the given value
     */
    public Result gt(Integer value) {
        if (isSingleResult()) {
            if (valueNumeric == null || valueNumeric <= value) {
                return emptyResult;
            }
            return this;
        }
        List<Result> matches = new ArrayList<>();
        for (Result r : this) {
            if (!r.gt(value).isEmpty()) {
                matches.add(r);
            }
        }
        if (matches.size() < 1) {
            return emptyResult;
        }
        return new Result(matches);
    }

    /**
     * @return true if result contains a coded value with the given concept id (if the result is a
     *         list, then returns true if <em>any</em> member has a matching coded value)
     */
    public boolean containsConcept(Integer conceptId) {
        if (isSingleResult()) {
            return (valueCoded != null && valueCoded.getConceptId().equals(conceptId));
        }
        for (Result r : this) {
            if (r.containsConcept(conceptId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return true if the result is equal to the given result or is a list containing a member
     *         equal to the given result
     */
    public boolean contains(Result result) {
        if (isSingleResult()) {
            return this.equals(result);
        }
        for (Result r : this) {
            if (r.contains(result)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return a result with all duplicates removed
     */
    public Result unique() {
        if (isSingleResult()) {
            return this;
        }
        Integer something = 1;
        Map<Result, Integer> map = new HashMap<>();
        for (Result r : this) {
            map.put(r, something);
        }
        List<Result> uniqueList = new ArrayList<>(map.keySet());
        return new Result(uniqueList);
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Result)) {
            return false;
        }
        Result r = (Result) obj;
        if (EmptyResult.clreplaced.isreplacedignableFrom(r.getClreplaced()) && this.isEmpty()) {
            return true;
        }
        if (EmptyResult.clreplaced.isreplacedignableFrom(this.getClreplaced()) && r.isEmpty()) {
            return true;
        }
        if (isSingleResult() && r.isSingleResult()) {
            if (datatype == null) {
                return false;
            }
            // both are single results
            switch(datatype) {
                case BOOLEAN:
                    return (valueBoolean.equals(r.valueBoolean));
                case CODED:
                    return (valueCoded.equals(r.valueCoded));
                case DATETIME:
                    return (valueDatetime.equals(r.valueDatetime));
                case NUMERIC:
                    return (valueNumeric.equals(r.valueNumeric));
                case TEXT:
                    return (valueText.equals(r.valueText));
                default:
                    return false;
            }
        }
        if (isSingleResult() || r.isSingleResult()) {
            // we already know they're not both single results, so if one is
            // single, it's not a match
            return false;
        }
        if (this.size() != r.size()) {
            return false;
        }
        // at this point, we have two results that are lists, so members must
        // match exactly
        for (int i = 0; i < this.size(); i++) {
            if (!this.get(i).equals(r.get(i))) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        if (isSingleResult()) {
            return new HashCodeBuilder().append(datatype).hashCode();
        } else {
            return super.hashCode();
        }
    }

    /**
     * @return the <em>index</em> element of a list. If the result is not a list, then this will
     *         return the result only if <em>index</em> is equal to zero (0); otherwise, returns an
     *         empty result
     * @see java.util.List#get(int)
     * @should get empty result for indexes out of range
     */
    @Override
    public Result get(int index) {
        if (isSingleResult()) {
            return (index == 0 ? this : emptyResult);
        }
        if (index >= this.size()) {
            return emptyResult;
        }
        return super.get(index);
    }

    /**
     * @return the chronologically (based on result date) first result
     * @should get the first result given multiple results
     * @should get the result given a single result
     * @should get an empty result given an empty result
     * @should not get the result with null result date given other results
     * @should get one result with null result dates for all results
     */
    public Result earliest() {
        if (isSingleResult()) {
            return this;
        }
        Result first = emptyResult();
        // default the returned result to the first item
        // in case all resultDates are null
        if (size() > 0) {
            first = get(0);
        }
        for (Result r : this) {
            if (r != null && r.getResultDate() != null && (first.getResultDate() == null || r.getResultDate().before(first.getResultDate()))) {
                first = r;
            }
        }
        return first;
    }

    /**
     * @return the chronologically (based on result date) last result
     * @should get the most recent result given multiple results
     * @should get the result given a single result
     * @should get an empty result given an empty result
     * @should get the result with null result date
     */
    public Result latest() {
        if (isSingleResult()) {
            return this;
        }
        Result last = emptyResult();
        // default the returned result to the first item
        // in case all resultDates are null
        if (size() > 0) {
            last = get(0);
        }
        for (Result r : this) {
            if ((last.getResultDate() == null || (r.getResultDate() != null && r.getResultDate().after(last.getResultDate())))) {
                last = r;
            }
        }
        return last;
    }

    /**
     * Convenience method to know if this Result represents multiple results or not
     *
     * @return true/false whether this is just one Result or more than one
     */
    private boolean isSingleResult() {
        return (this.size() < 1);
    }
}

19 Source : Result.java
with Apache License 2.0
from isstac

public boolean contains(Concept concept) {
    return containsConcept(concept.getConceptId());
}

19 Source : Result.java
with Apache License 2.0
from isstac

/**
 * Overrides the coded representation of ths result without changing the default datatype
 *
 * @param valueCoded
 */
public void setValueCoded(Concept valueCoded) {
    this.valueCoded = valueCoded;
}

19 Source : ProposingConceptException.java
with Apache License 2.0
from isstac

/**
 * Represents a obs that should be a proposed concept
 */
public clreplaced ProposingConceptException extends APIException {

    public static final long serialVersionUID = 120002000200L;

    private Concept concept;

    private String valueName;

    /**
     * Default constructor that takes in the required parameters
     *
     * @param concept the question for this proposed concept
     * @param valueName the proposed text for this concept
     */
    public ProposingConceptException(Concept concept, String valueName) {
        this.concept = concept;
        this.valueName = valueName;
    }

    /**
     * @return the concept
     */
    public Concept getConcept() {
        return concept;
    }

    /**
     * @param concept the concept to set
     */
    public void setConcept(Concept concept) {
        this.concept = concept;
    }

    /**
     * @return the valueName
     */
    public String getValueName() {
        return valueName;
    }

    /**
     * @param valueName the valueName to set
     */
    public void setValueName(String valueName) {
        this.valueName = valueName;
    }
}

19 Source : ProposingConceptException.java
with Apache License 2.0
from isstac

/**
 * @param concept the concept to set
 */
public void setConcept(Concept concept) {
    this.concept = concept;
}

19 Source : ConceptDatatype.java
with Apache License 2.0
from isstac

/**
 * @see BaseOpenmrsDatatype#doGetTextSummary(Object)
 * @should use the name in summary instance
 */
@Override
public Summary doGetTextSummary(Concept concept) {
    String name = "";
    if (concept != null && concept.getName() != null) {
        name = concept.getName().getName();
    }
    return new CustomDatatype.Summary(name, true);
}

18 Source : OrderFrequenciesLoaderIntegrationTest.java
with MIT License
from mekomsolutions

public clreplaced OrderFrequenciesLoaderIntegrationTest extends DomainBaseModuleContextSensitiveTest {

    @Autowired
    @Qualifier("orderService")
    private OrderService os;

    @Autowired
    @Qualifier("conceptService")
    private ConceptService cs;

    @Autowired
    private OrderFrequenciesLoader loader;

    private Concept hourlyConcept;

    private Concept bidailyConcept;

    @Before
    public void setup() {
        // Concepts to be used as a 'frequency'
        {
            hourlyConcept = new Concept();
            hourlyConcept.setShortName(new ConceptName("Hourly", Locale.ENGLISH));
            hourlyConcept.setConceptClreplaced(cs.getConceptClreplacedByName("Frequency"));
            hourlyConcept.setDatatype(cs.getConceptDatatypeByName("N/A"));
            hourlyConcept = cs.saveConcept(hourlyConcept);
        }
        {
            bidailyConcept = new Concept();
            bidailyConcept.setShortName(new ConceptName("Bidaily", Locale.ENGLISH));
            bidailyConcept.setConceptClreplaced(cs.getConceptClreplacedByName("Frequency"));
            bidailyConcept.setDatatype(cs.getConceptDatatypeByName("N/A"));
            bidailyConcept = cs.saveConcept(bidailyConcept);
        }
        // An order frequency to be edited
        {
            Concept freqConcept = new Concept();
            freqConcept.setShortName(new ConceptName("Weekly", Locale.ENGLISH));
            freqConcept.setConceptClreplaced(cs.getConceptClreplacedByName("Frequency"));
            freqConcept.setDatatype(cs.getConceptDatatypeByName("N/A"));
            freqConcept = cs.saveConcept(freqConcept);
            OrderFrequency freq = new OrderFrequency();
            freq.setUuid("136ebdb7-e989-47cf-8ec2-4e8b2ffe0ab3");
            freq.setConcept(freqConcept);
            freq.setFrequencyPerDay(1.0);
            freq = os.saveOrderFrequency(freq);
        }
        // An order frequency to be retired
        {
            Concept freqConcept = new Concept();
            freqConcept.setShortName(new ConceptName("Monthly", Locale.ENGLISH));
            freqConcept.setConceptClreplaced(cs.getConceptClreplacedByName("Frequency"));
            freqConcept.setDatatype(cs.getConceptDatatypeByName("N/A"));
            freqConcept = cs.saveConcept(freqConcept);
            OrderFrequency freq = new OrderFrequency();
            freq.setUuid("4b33b729-1fe3-4fa5-acc4-084beb069b68");
            freq.setConcept(freqConcept);
            freq.setFrequencyPerDay(1.0);
            freq = os.saveOrderFrequency(freq);
        }
    }

    @Test
    public void load_shouldLoadOrderFrequenciesAccordingToCsvFiles() {
        // Replay
        loader.load();
        // created frequency
        {
            OrderFrequency freq = os.getOrderFrequencyByConcept(hourlyConcept);
            replacedert.replacedertNotNull(freq);
            replacedert.replacedertEquals(0, Double.compare(24.0, freq.getFrequencyPerDay()));
        }
        // retired frequency
        {
            OrderFrequency freq = os.getOrderFrequencyByUuid("4b33b729-1fe3-4fa5-acc4-084beb069b68");
            replacedert.replacedertNotNull(freq);
            replacedert.replacedertTrue(freq.getRetired());
        }
        // edited frequency
        {
            OrderFrequency freq = os.getOrderFrequencyByUuid("136ebdb7-e989-47cf-8ec2-4e8b2ffe0ab3");
            replacedert.replacedertNotNull(freq);
            replacedert.replacedertEquals(bidailyConcept, freq.getConcept());
            replacedert.replacedertEquals(0, Double.compare(0.5, freq.getFrequencyPerDay()));
        }
    }
}

18 Source : NestedConceptLineProcessorTest.java
with MIT License
from mekomsolutions

public void fill_shouldHandleMissingHeaders() {
    // Setup
    String[] headerLine = {};
    String[] line = {};
    // Replay
    NestedConceptLineProcessor p = new NestedConceptLineProcessor(cs, new ConceptListParser(cs));
    Concept c = p.fill(new Concept(), new CsvLine(headerLine, line));
    replacedert.replacedertNull(c.getAnswers());
    replacedert.replacedertNull(c.getSetMembers());
}

18 Source : MappingsConceptLineProcessorTest.java
with MIT License
from mekomsolutions

public void getConcept_shouldHandleMissingHeaders() {
    // Setup
    String[] headerLine = {};
    String[] line = {};
    // Replay
    MappingsConceptLineProcessor p = new MappingsConceptLineProcessor(cs, new ConceptMapListParser(cs));
    Concept c = p.fill(new Concept(), new CsvLine(headerLine, line));
    replacedert.replacedertNull(c.getConceptMappings());
}

18 Source : ConceptNumericLineProcessorTest.java
with MIT License
from mekomsolutions

@Test
public void fill_shouldHandleMissingHeaders() {
    // Setup
    String[] headerLine = {};
    String[] line = {};
    // Replay
    ConceptNumericLineProcessor p = new ConceptNumericLineProcessor(cs);
    Concept c = p.fill(new Concept(), new CsvLine(headerLine, line));
    // Verif
    replacedert.replacedertFalse(c instanceof ConceptNumeric);
}

18 Source : Utils.java
with MIT License
from mekomsolutions

/**
 * Fetches a concept trying various routes for its "id".
 *
 * @param id The concept mapping ("cambodia:123"), concept name or concept UUID.
 * @param service
 * @return The {@link Concept} instance if found, null otherwise.
 */
public static Concept fetchConcept(String id, ConceptService service) {
    Concept instance = null;
    if (instance == null) {
        instance = service.getConceptByUuid(id);
    }
    if (instance == null) {
        instance = service.getConceptByName(id);
    }
    if (instance == null) {
        instance = getConceptByMapping(id, service);
    }
    return instance;
}

18 Source : Utils.java
with MIT License
from mekomsolutions

/**
 * @param mapping The concept mapping, eg. "cambodia:123"
 * @param service
 * @return The {@link Concept} instance if found, null otherwise.
 */
public static Concept getConceptByMapping(String mapping, ConceptService service) {
    Concept instance = null;
    if (StringUtils.isEmpty(mapping)) {
        return instance;
    }
    String[] parts = mapping.split(":");
    if (parts.length == 2) {
        instance = service.getConceptByMapping(parts[1].trim(), parts[0].trim());
    }
    return instance;
}

18 Source : Utils.java
with MIT License
from mekomsolutions

/**
 * Guesses a 'best match' description for a given concept.
 *
 * @param concept Concept Object.
 * @param locale
 * @return conceptDescription string if found, null otherwise.
 */
public static String getBestMatchDescription(Concept concept, Locale locale) {
    String conceptDescription = null;
    if (concept.getDescription(locale, true) != null) {
        conceptDescription = concept.getDescription(locale, true).getDescription();
    } else if (concept.getDescription(locale) != null) {
        conceptDescription = concept.getDescription(locale).getDescription();
    } else {
        conceptDescription = getBestMatchName(concept, locale);
    }
    return conceptDescription;
}

18 Source : OrderFrequencyLineProcessor.java
with MIT License
from mekomsolutions

@Override
public OrderFrequency fill(OrderFrequency freq, CsvLine line) throws IllegalArgumentException {
    Concept conceptFreq = Utils.fetchConcept(line.get(HEADER_CONCEPT_FREQ), conceptService);
    freq.setConcept(conceptFreq);
    freq.setFrequencyPerDay(line.getDouble(HEADER_FREQ_PER_DAY));
    return freq;
}

18 Source : NestedConceptLineProcessor.java
with MIT License
from mekomsolutions

public Concept fill(Concept concept, CsvLine line) throws IllegalArgumentException {
    if (!CollectionUtils.isEmpty(concept.getAnswers())) {
        concept.getAnswers().clear();
    }
    String childrenStr;
    childrenStr = line.get(HEADER_ANSWERS);
    if (!StringUtils.isEmpty(childrenStr)) {
        for (Concept child : listParser.parseList(childrenStr)) {
            concept.addAnswer(new ConceptAnswer(child));
        }
    }
    if (!CollectionUtils.isEmpty(concept.getConceptSets())) {
        concept.getConceptSets().clear();
        concept.setSet(false);
    }
    childrenStr = line.get(HEADER_MEMBERS);
    if (!StringUtils.isEmpty(childrenStr)) {
        for (Concept child : listParser.parseList(childrenStr)) {
            concept.addSetMember(child);
        }
        concept.setSet(true);
    }
    return concept;
}

18 Source : ConceptValidatorTest.java
with Apache License 2.0
from isstac

/**
 * Tests methods on the {@link ConceptValidator} clreplaced.
 */
public clreplaced ConceptValidatorTest extends BaseContextSensitiveTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private ConceptValidator validator;

    private Concept concept;

    private Errors errors;

    @Autowired
    private ConceptService conceptService;

    private Concept cd4Count;

    private Concept weight;

    @Before
    public void setUp() {
        validator = new ConceptValidator();
        concept = new Concept();
        errors = new BindException(concept, "concept");
        cd4Count = conceptService.getConcept(5497);
        weight = conceptService.getConcept(5089);
    }

    @Test
    public void validate_shouldFailIfTheObjectParameterIsNull() {
        expectedException.expect(IllegalArgumentException.clreplaced);
        expectedException.expectMessage("The parameter obj should not be null and must be of type" + Concept.clreplaced);
        validator.validate(null, errors);
    }

    @Test
    public void shouldFailIfNamesAreEmpty() {
        validator.validate(concept, errors);
        replacedertThat(errors, hasGlobalErrors("Concept.name.atLeastOneRequired"));
    }

    @Test
    public void validate_shouldFailIfTheConceptDatatypeIsNull() {
        concept.addName(new ConceptName("some name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced(1));
        validator.validate(concept, errors);
        replacedertThat(errors, hasFieldErrors("datatype", "Concept.datatype.empty"));
    }

    @Test
    public void validate_shouldFailIfTheConceptClreplacedIsNull() {
        concept.addName(new ConceptName("some name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setDatatype(new ConceptDatatype(1));
        validator.validate(concept, errors);
        replacedertThat(errors, hasFieldErrors("conceptClreplaced", "Concept.conceptClreplaced.empty"));
    }

    @Test
    public void validate_shouldFailIfAnyNameIsAnEmptyString() {
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced(1));
        concept.setDatatype(new ConceptDatatype(1));
        concept.addName(new ConceptName("name", Context.getLocale()));
        concept.addName(new ConceptName("", Context.getLocale()));
        validator.validate(concept, errors);
        replacedertThat(errors, hasGlobalErrors("Concept.name.empty"));
    }

    @Test
    public void validate_shouldFailIfAnyNameIsANullValue() {
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced(1));
        concept.setDatatype(new ConceptDatatype(1));
        concept.addName(new ConceptName("name", Context.getLocale()));
        concept.addName(new ConceptName(null, Context.getLocale()));
        validator.validate(concept, errors);
        replacedertThat(errors, hasGlobalErrors("Concept.name.empty"));
    }

    @Test
    public void validate_shouldFailIfThereIsADuplicateUnretiredConceptNameInTheLocale() {
        Context.setLocale(new Locale("en", "GB"));
        concept = cd4Count;
        String duplicateName = concept.getFullySpecifiedName(Context.getLocale()).getName();
        ConceptName newName = new ConceptName(duplicateName, Context.getLocale());
        newName.setDateCreated(Calendar.getInstance().getTime());
        newName.setCreator(Context.getAuthenticatedUser());
        concept.addName(newName);
        errors = new BindException(concept, "concept");
        expectedException.expect(DuplicateConceptNameException.clreplaced);
        expectedException.expectMessage("'" + duplicateName + "' is a duplicate name in locale '" + Context.getLocale() + "'");
        validator.validate(concept, errors);
    }

    @Test
    public void validate_shouldFailIfAnyNamesInTheSameLocaleForThisConceptAreSimilar() {
        concept.addName(new ConceptName("same name", Context.getLocale()));
        concept.addName(new ConceptName("same name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        expectedException.expect(DuplicateConceptNameException.clreplaced);
        expectedException.expectMessage("'same name' is a duplicate name in locale '" + Context.getLocale() + "'");
        validator.validate(concept, errors);
    }

    @Test
    public void validate_shouldFailIfThereIsADuplicateUnretiredFullySpecifiedNameInTheSameLocale() {
        Context.setLocale(new Locale("en", "GB"));
        replacedert.replacedertEquals(true, cd4Count.getFullySpecifiedName(Context.getLocale()).isFullySpecifiedName());
        String duplicateName = cd4Count.getFullySpecifiedName(Context.getLocale()).getName();
        Concept anotherConcept = weight;
        anotherConcept.getFullySpecifiedName(Context.getLocale()).setName(duplicateName);
        Errors errors = new BindException(anotherConcept, "concept");
        expectedException.expect(DuplicateConceptNameException.clreplaced);
        expectedException.expectMessage("'" + duplicateName + "' is a duplicate name in locale '" + Context.getLocale() + "'");
        validator.validate(anotherConcept, errors);
    }

    @Test
    public void validate_shouldFailIfThereIsADuplicateUnretiredPreferredNameInTheSameLocale() {
        Context.setLocale(new Locale("en", "GB"));
        Concept concept = cd4Count;
        ConceptName preferredName = new ConceptName("preferred name", Context.getLocale());
        concept.setPreferredName(preferredName);
        conceptService.saveConcept(concept);
        replacedert.replacedertEquals("preferred name", concept.getPreferredName(Context.getLocale()).getName());
        Concept anotherConcept = weight;
        anotherConcept.getFullySpecifiedName(Context.getLocale()).setName("preferred name");
        Errors errors = new BindException(anotherConcept, "concept");
        expectedException.expect(DuplicateConceptNameException.clreplaced);
        expectedException.expectMessage("'" + preferredName + "' is a duplicate name in locale '" + Context.getLocale() + "'");
        validator.validate(anotherConcept, errors);
    }

    @Test
    public void validate_shouldFailIfThereIsNoNameExplicitlyMarkedAsFullySpecified() {
        Concept concept = cd4Count;
        for (ConceptName name : concept.getNames()) {
            name.setConceptNameType(null);
        }
        Errors errors = new BindException(concept, "concept");
        validator.validate(concept, errors);
        replacedertThat(errors, hasGlobalErrors("Concept.error.no.FullySpecifiedName"));
    }

    @Test
    public void validate_shouldPreplacedIfTheConceptIsBeingUpdatedWithNoNameChange() {
        Concept conceptToUpdate = cd4Count;
        conceptToUpdate.setCreator(Context.getAuthenticatedUser());
        Errors errors = new BindException(conceptToUpdate, "concept");
        validator.validate(conceptToUpdate, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfTheConceptHasAtleastOneFullySpecifiedNameAddedToIt() {
        concept.addName(new ConceptName("one name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfTheDuplicateConceptNameIsNeitherPreferredNorFullySpecified() {
        Context.setLocale(new Locale("en", "GB"));
        Concept concept = cd4Count;
        // use a synonym as the duplicate name
        ConceptName duplicateName = concept.getSynonyms(Context.getLocale()).iterator().next();
        replacedert.replacedertEquals(true, duplicateName.isSynonym());
        Concept anotherConcept = weight;
        anotherConcept.getFullySpecifiedName(Context.getLocale()).setName(duplicateName.getName());
        Errors errors = new BindException(anotherConcept, "concept");
        validator.validate(anotherConcept, errors);
        replacedert.replacedertEquals(false, errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfTheConceptWithADuplicateNameIsRetired() {
        Context.setLocale(new Locale("en", "GB"));
        Concept concept = cd4Count;
        concept.setRetired(true);
        conceptService.saveConcept(concept);
        String duplicateName = concept.getFullySpecifiedName(Context.getLocale()).getName();
        Concept anotherConcept = weight;
        anotherConcept.getFullySpecifiedName(Context.getLocale()).setName(duplicateName);
        Errors errors = new BindException(anotherConcept, "concept");
        validator.validate(anotherConcept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfTheConceptBeingValidatedIsRetiredAndHasADuplicateName() {
        Context.setLocale(new Locale("en", "GB"));
        Concept concept = cd4Count;
        conceptService.saveConcept(concept);
        String duplicateName = concept.getFullySpecifiedName(Context.getLocale()).getName();
        Concept anotherConcept = weight;
        anotherConcept.setRetired(true);
        anotherConcept.getFullySpecifiedName(Context.getLocale()).setName(duplicateName);
        Errors errors = new BindException(anotherConcept, "concept");
        validator.validate(anotherConcept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfTheConceptHasASynonymThatIsAlsoAShortName() {
        concept.addName(new ConceptName("CD4", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        // Add the short name. Because the short name is not counted as a Synonym.
        // ConceptValidator will not record any errors.
        ConceptName name = new ConceptName("CD4", Context.getLocale());
        name.setConceptNameType(ConceptNameType.SHORT);
        concept.addName(name);
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldFailIfATermIsMappedMultipleTimesToTheSameConcept() {
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        concept.addName(new ConceptName("my name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        ConceptMap map1 = new ConceptMap(conceptService.getConceptReferenceTerm(1), conceptService.getConceptMapType(1));
        concept.addConceptMapping(map1);
        ConceptMap map2 = new ConceptMap(conceptService.getConceptReferenceTerm(1), conceptService.getConceptMapType(1));
        concept.addConceptMapping(map2);
        validator.validate(concept, errors);
        replacedertThat(errors, hasFieldErrors("conceptMappings[1]"));
    }

    @Test
    public void validate_shouldPreplacedIfTheDuplicateNameInTheLocaleForTheConceptBeingValidatedIsVoided() {
        ConceptName otherName = conceptService.getConceptName(1439);
        // sanity check since names should only be unique amongst preferred and fully specified names
        replacedert.replacedertTrue(otherName.isFullySpecifiedName() || otherName.isPreferred());
        replacedert.replacedertFalse(otherName.getVoided());
        replacedert.replacedertFalse(otherName.getConcept().getRetired());
        // change to a duplicate name in the same locale
        ConceptName duplicateName = conceptService.getConceptName(2477);
        duplicateName.setName(otherName.getName());
        Concept concept = duplicateName.getConcept();
        concept.setPreferredName(duplicateName);
        // ensure that the name has been marked as preferred in its locale
        replacedert.replacedertEquals(duplicateName, concept.getPreferredName(duplicateName.getLocale()));
        replacedert.replacedertTrue(duplicateName.isPreferred());
        duplicateName.setVoided(true);
        Errors errors = new BindException(concept, "concept");
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldFailIfThereIsADuplicateUnretiredConceptNameInTheSameLocaleDifferentThanTheSystemLocale() {
        Context.setLocale(new Locale("pl"));
        Locale en = new Locale("en", "GB");
        Concept concept = cd4Count;
        replacedert.replacedertEquals(true, concept.getFullySpecifiedName(en).isFullySpecifiedName());
        String duplicateName = concept.getFullySpecifiedName(en).getName();
        Concept anotherConcept = weight;
        anotherConcept.getFullySpecifiedName(en).setName(duplicateName);
        Errors errors = new BindException(anotherConcept, "concept");
        expectedException.expect(DuplicateConceptNameException.clreplaced);
        expectedException.expectMessage("'" + duplicateName + "' is a duplicate name in locale '" + en + "'");
        validator.validate(concept, errors);
        validator.validate(anotherConcept, errors);
    }

    @Test
    public void validate_shouldPreplacedForANewConceptWithAMapCreatedWithDeprecatedConceptMapMethods() {
        concept.addName(new ConceptName("test name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        ConceptMap map = new ConceptMap();
        map.getConceptReferenceTerm().setCode("unique code");
        map.getConceptReferenceTerm().setConceptSource(conceptService.getConceptSource(1));
        concept.addConceptMapping(map);
        ValidateUtil.validate(concept);
    }

    @Test
    public void validate_shouldPreplacedForAnEditedConceptWithAMapCreatedWithDeprecatedConceptMapMethods() {
        Concept concept = cd4Count;
        ConceptMap map = new ConceptMap();
        map.getConceptReferenceTerm().setCode("unique code");
        map.getConceptReferenceTerm().setConceptSource(conceptService.getConceptSource(1));
        concept.addConceptMapping(map);
        ValidateUtil.validate(concept);
    }

    @Test
    public void validate_shouldNotFailIfATermHasTwoNewMappingsOnIt() {
        concept.addName(new ConceptName("my name", Context.getLocale()));
        ConceptReferenceTerm newTerm = new ConceptReferenceTerm(conceptService.getConceptSource(1), "1234", "term one two three four");
        ConceptMap map1 = new ConceptMap(newTerm, conceptService.getConceptMapType(1));
        concept.addConceptMapping(map1);
        ConceptReferenceTerm newTermTwo = new ConceptReferenceTerm(conceptService.getConceptSource(1), "12345", "term one two three four five");
        ConceptMap map2 = new ConceptMap(newTermTwo, conceptService.getConceptMapType(1));
        concept.addConceptMapping(map2);
        validator.validate(concept, errors);
        replacedertThat(errors, not(hasFieldErrors("conceptMappings[1]")));
    }

    @Test
    public void validate_shouldPreplacedValidationIfFieldLengthsAreCorrect() {
        concept.addName(new ConceptName("CD4", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setVersion("version");
        concept.setRetireReason("retireReason");
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldFailValidationIfFieldLengthsAreNotCorrect() {
        concept.addName(new ConceptName("CD4", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        concept.setVersion("too long text too long text too long text too long text");
        concept.setRetireReason("too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text too long text");
        validator.validate(concept, errors);
        replacedertThat(errors, hasFieldErrors("version", "error.exceededMaxLengthOfField"));
        replacedertThat(errors, hasFieldErrors("retireReason", "error.exceededMaxLengthOfField"));
    }

    @Test
    public void validate_shouldPreplacedIfFullySpecifiedNameIsTheSamereplacedhortName() {
        ConceptName conceptFullySpecifiedName = new ConceptName("YES", new Locale("pl"));
        conceptFullySpecifiedName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED);
        ConceptName conceptShortName = new ConceptName("yes", new Locale("pl"));
        conceptShortName.setConceptNameType(ConceptNameType.SHORT);
        concept.addName(conceptFullySpecifiedName);
        concept.addName(conceptShortName);
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldPreplacedIfDifferentConceptsHaveTheSameShortNames() {
        Context.setLocale(new Locale("en", "GB"));
        List<Concept> concepts = conceptService.getConceptsByName("HSM");
        replacedert.replacedertEquals(1, concepts.size());
        replacedert.replacedertEquals(true, concepts.get(0).getShortNameInLocale(Context.getLocale()).getName().equalsIgnoreCase("HSM"));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        ConceptName conceptFullySpecifiedName = new ConceptName("holosystolic murmur", Context.getLocale());
        conceptFullySpecifiedName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED);
        ConceptName conceptShortName = new ConceptName("HSM", Context.getLocale());
        conceptShortName.setConceptNameType(ConceptNameType.SHORT);
        concept.addName(conceptFullySpecifiedName);
        concept.addName(conceptShortName);
        concept.addDescription(new ConceptDescription("some description", null));
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldFailIfCodedConceptContainsItselfAsAnAnswer() {
        Concept concept = conceptService.getConcept(30);
        ConceptAnswer conceptAnswer = new ConceptAnswer(concept);
        concept.addAnswer(conceptAnswer);
        Errors errors = new BindException(concept, "concept");
        validator.validate(concept, errors);
        replacedertThat(errors, hasGlobalErrors("Concept.contains.itself.as.answer"));
    }

    @Test
    public void validate_shouldNotFailIfAnyDescriptionIsNotEnteredWhileCreatingANewConcept() {
        concept.addName(new ConceptName("some name", Context.getLocale()));
        validator.validate(concept, errors);
        replacedertThat(errors, not(hasFieldErrors("description")));
    }

    @Test
    public void validate_shouldPreplacedIfNoneofTheConceptDescriptionsIsNull() {
        concept.addName(new ConceptName("some name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("some description", null));
        concept.setConceptClreplaced(new ConceptClreplaced());
        concept.setDatatype(new ConceptDatatype());
        validator.validate(concept, errors);
        replacedert.replacedertFalse(errors.hasErrors());
    }

    @Test
    public void validate_shouldNotFailIfBlankConceptDescriptionIsPreplaceded() {
        concept.addName(new ConceptName("some name", Context.getLocale()));
        concept.addDescription(new ConceptDescription("   ", null));
        validator.validate(concept, errors);
        replacedertThat(errors, not(hasFieldErrors("description")));
    }
}

18 Source : ConceptDAOTest.java
with Apache License 2.0
from isstac

@Test
public void purgeConcept_shouldPurgeConcept() {
    Concept concept = dao.getConcept(11);
    dao.purgeConcept(concept);
    replacedertNull(dao.getConcept(11));
}

18 Source : FormUtil.java
with Apache License 2.0
from isstac

/**
 * Turn the given concept into a string acceptable to for hl7 and forms
 *
 * @param concept Concept to convert to a string
 * @param locale Locale to use for the concept name
 * @return String representation of the given concept
 */
public static String conceptToString(Concept concept, Locale locale) {
    ConceptName localizedName = concept.getName(locale, false);
    return conceptToString(concept, localizedName);
}

18 Source : FormUtil.java
with Apache License 2.0
from isstac

/**
 * Turn the given concept/concept-name pair into a string acceptable for hl7 and forms
 *
 * @param concept Concept to convert to a string
 * @param localizedName specific localized concept-name
 * @return String representation of the given concept
 */
public static String conceptToString(Concept concept, ConceptName localizedName) {
    // + "^"
    return concept.getConceptId() + "^" + localizedName.getName() + "^" + HL7Constants.HL7_LOCAL_CONCEPT;
}

18 Source : ProgramWorkflowServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.ProgramWorkflowService#getProgramWorkflowsByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<ProgramWorkflow> getProgramWorkflowsByConcept(Concept concept) {
    return dao.getProgramWorkflowsByConcept(concept);
}

17 Source : MappingsConceptLineProcessorTest.java
with MIT License
from mekomsolutions

@Test
public void fill_shouldHandleNoSameAsMappings() {
    // Setup
    String[] headerLine = { "Same as mappings" };
    String[] line = { null };
    // Replay
    MappingsConceptLineProcessor p = new MappingsConceptLineProcessor(cs, new ConceptMapListParser(cs));
    Concept c = p.fill(new Concept(), new CsvLine(headerLine, line));
    // Verif
    replacedert.replacedertTrue(CollectionUtils.isEmpty(c.getConceptMappings()));
}

17 Source : MappingsConceptLineProcessor.java
with MIT License
from mekomsolutions

public Concept fill(Concept concept, CsvLine line) throws IllegalArgumentException {
    if (!CollectionUtils.isEmpty(concept.getConceptMappings())) {
        concept.getConceptMappings().clear();
    }
    String mappingsStr = line.get(HEADER_MAPPINGS_SAMEAS);
    if (!StringUtils.isEmpty(mappingsStr)) {
        for (ConceptMap mapping : listParser.parseList(mappingsStr)) {
            concept.addConceptMapping(mapping);
        }
    }
    return concept;
}

17 Source : AllergyValidatorTest.java
with Apache License 2.0
from isstac

private Concept createMockConcept(String uuid) {
    Concept concept = mock(Concept.clreplaced);
    when(concept.getUuid()).thenReturn(uuid != null ? uuid : "some uuid");
    when(concept.getName()).thenReturn(new ConceptName());
    return concept;
}

17 Source : ConceptServiceImplTest.java
with Apache License 2.0
from isstac

/**
 * @see ConceptServiceImpl#getPrevConcept(Concept)
 */
@Test
public void getPrevConcept_shouldReturnTheConceptPreviousToTheGivenConcept() {
    Integer conceptId = 4;
    Integer prevConceptId = 3;
    Concept returnedConcept = conceptService.getPrevConcept(conceptService.getConcept(conceptId));
    replacedertEquals(returnedConcept, conceptService.getConcept(prevConceptId));
}

17 Source : AuthorizationAdviceTest.java
with Apache License 2.0
from isstac

@Test
public void before_shouldNotifyListenersAboutCheckedPrivileges() {
    listener1.hasPrivileges.clear();
    listener1.lacksPrivileges.clear();
    listener2.hasPrivileges.clear();
    listener2.lacksPrivileges.clear();
    Concept concept = Context.getConceptService().getConcept(3);
    replacedertThat("listener1", listener1.hasPrivileges, containsInAnyOrder(PrivilegeConstants.GET_CONCEPTS));
    replacedertThat("listener2", listener2.hasPrivileges, containsInAnyOrder(PrivilegeConstants.GET_CONCEPTS));
    replacedertThat(listener1.lacksPrivileges, empty());
    replacedertThat(listener2.lacksPrivileges, empty());
    listener1.hasPrivileges.clear();
    listener2.hasPrivileges.clear();
    Context.getConceptService().saveConcept(concept);
    String[] privileges = { PrivilegeConstants.MANAGE_CONCEPTS, PrivilegeConstants.GET_OBS, PrivilegeConstants.GET_CONCEPT_ATTRIBUTE_TYPES };
    replacedertThat("listener1", listener1.hasPrivileges, containsInAnyOrder(privileges));
    replacedertThat("listener2", listener2.hasPrivileges, containsInAnyOrder(privileges));
    replacedertThat(listener1.lacksPrivileges, empty());
    replacedertThat(listener2.lacksPrivileges, empty());
}

17 Source : OrderFrequencyValidator.java
with Apache License 2.0
from isstac

/**
 * Checks the order frequency object for any inconsistencies/errors
 *
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail if orderFrequency is null
 * @should fail if concept is null
 * @should fail if the concept is not of clreplaced frequency
 * @should fail if concept is used by another frequency
 * @should preplaced for a valid new order frequency
 * @should preplaced for a valid existing order frequency
 * @should be invoked when an order frequency is saved
 * @should preplaced validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
@Override
public void validate(Object obj, Errors errors) {
    OrderFrequency orderFrequency = (OrderFrequency) obj;
    if (orderFrequency == null) {
        errors.reject("error.general");
    } else {
        ValidationUtils.rejectIfEmpty(errors, "concept", "Concept.noConceptSelected");
        Concept concept = orderFrequency.getConcept();
        if (concept != null) {
            if (!ConceptClreplaced.FREQUENCY_UUID.equals(concept.getConceptClreplaced().getUuid())) {
                errors.rejectValue("concept", "OrderFrequency.concept.shouldBeClreplacedFrequency");
            }
            OrderFrequency of = Context.getOrderService().getOrderFrequencyByConcept(concept);
            if (of != null && !of.equals(orderFrequency)) {
                errors.rejectValue("concept", "OrderFrequency.concept.shouldNotBeShared");
            }
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClreplaced(), "retireReason");
    }
}

17 Source : ProgramWorkflowServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.ProgramWorkflowService#getProgramWorkflowStatesByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<ProgramWorkflowState> getProgramWorkflowStatesByConcept(Concept concept) {
    return dao.getProgramWorkflowStatesByConcept(concept);
}

17 Source : ProgramWorkflowServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.ProgramWorkflowService#getProgramsByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<Program> getProgramsByConcept(Concept concept) {
    return dao.getProgramsByConcept(concept);
}

17 Source : OrderServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.OrderService#getOrderFrequencyByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public OrderFrequency getOrderFrequencyByConcept(Concept concept) {
    return dao.getOrderFrequencyByConcept(concept);
}

16 Source : NestedConceptLineProcessorTest.java
with MIT License
from mekomsolutions

@Test
public void fill_shouldHandleNoChildren() {
    // Setup
    String[] headerLine = { "Answers", "Members" };
    String[] line = { null, null };
    // Replay
    NestedConceptLineProcessor p = new NestedConceptLineProcessor(cs, new ConceptListParser(cs));
    Concept c = p.fill(new Concept(), new CsvLine(headerLine, line));
    // Verif
    replacedert.replacedertFalse(c.getSet());
    replacedert.replacedertEquals(0, c.getSetMembers().size());
    replacedert.replacedertEquals(0, c.getAnswers().size());
}

16 Source : Utils.java
with MIT License
from mekomsolutions

/**
 * Guesses a 'best match' name for a given concept.
 *
 * @param concept Concept Object.
 * @param locale
 * @return conceptName string if found, null otherwise.
 */
public static String getBestMatchName(Concept concept, Locale locale) {
    ConceptName conceptName = null;
    if (concept.getPreferredName(locale) != null) {
        conceptName = concept.getPreferredName(locale);
    } else if (concept.getFullySpecifiedName(locale) != null) {
        conceptName = concept.getFullySpecifiedName(locale);
    } else if (concept.getName(locale, true) != null) {
        conceptName = concept.getName(locale, true);
    } else if (concept.getName(locale) != null) {
        conceptName = concept.getName(locale);
    } else {
        conceptName = concept.getName();
    }
    return conceptName.getName();
}

16 Source : InitializerServiceImpl.java
with MIT License
from mekomsolutions

@Override
public Concept getConceptFromKey(String key, Concept defaultInstance) {
    String val = getValueFromKey(key);
    if (StringUtils.isEmpty(val)) {
        return defaultInstance;
    }
    Concept instance = Utils.fetchConcept(val, Context.getConceptService());
    if (instance != null) {
        return instance;
    } else {
        return defaultInstance;
    }
}

16 Source : ConceptServiceImplTest.java
with Apache License 2.0
from isstac

/**
 * @see ConceptServiceImpl#getNextConcept(Concept)
 */
@Test
public void getNextConcept_shouldReturnTheConceptNextToTheGivenConcept() {
    Integer conceptId = 3;
    Integer nextConceptId = 4;
    Concept returnedConcept = conceptService.getNextConcept(conceptService.getConcept(conceptId));
    replacedertEquals(returnedConcept, conceptService.getConcept(nextConceptId));
}

16 Source : FormServiceTest.java
with Apache License 2.0
from isstac

/**
 * @see FormService#getFormsContainingConcept(Concept)
 */
@Test
public void getFormsContainingConcept_shouldGetAllFormsForConcept() {
    Concept concept = Context.getConceptService().getConcept(3);
    replacedertEquals(1, Context.getFormService().getFormsContainingConcept(concept).size());
}

16 Source : HibernateConceptDAOTest.java
with Apache License 2.0
from isstac

/**
 * @see HibernateConceptDAO#getDrugs(String,Concept,boolean,boolean,boolean,Integer,Integer)
 */
@Test
public void getDrugs_shouldReturnDrugIfPhraseMatchDrugNameNoNeedToMatchBothConceptNameAndDrugName() {
    // This concept does not contain concept_name with "Triomune"
    Concept concept2 = dao.getConcept(3);
    // In this test there is no any concept_name match with "Triomune" but
    // Drug name match with "Trimonue" so no need to match both drug_name
    // and the concept_name to find drug
    List<Drug> drugList = dao.getDrugs("Triomune", concept2, true, true, false, 0, 10);
    replacedert.replacedertEquals(1, drugList.size());
}

16 Source : HibernateConceptDAOTest.java
with Apache License 2.0
from isstac

/**
 * @see HibernateConceptDAO#getDrugs(String,Concept,boolean,boolean,boolean,Integer,Integer)
 */
@Test
public void getDrugs_shouldReturnDrugIfPhaseMatchConceptNameNoNeedToMatchBothConceptNameAndDrugName() {
    Concept concept4 = dao.getConcept(7);
    // In this test, there is no any drug_name with "VOIDED" but concept_name
    // match with "VOIDED" so this prove no need to match both drug_name and the
    // concept_name
    List<Drug> drugList = dao.getDrugs("VOIDED", concept4, true, true, false, 0, 10);
    replacedert.replacedertEquals(1, drugList.size());
}

16 Source : HibernateConceptDAOTest.java
with Apache License 2.0
from isstac

/**
 * @see HibernateConceptDAO#getDrugs(String,Concept,boolean,boolean,boolean,Integer,Integer)
 */
@Test
public void getDrugs_shouldReturnDrugIf_eitherDrugNameOrConceptNameMatchesThePhaseNotBoth() {
    Concept concept = dao.getConcept(3);
    // concept has "COUGH SYRUP" as a concept_name and also Drug has
    // Drug_name as "COUGH" so return two distinct drugs that means search
    // either drug name or concept name match the phase
    List<Drug> drugList = dao.getDrugs("COUGH", concept, true, true, false, 0, 10);
    replacedert.replacedertEquals(2, drugList.size());
}

16 Source : HibernateConceptDAOTest.java
with Apache License 2.0
from isstac

/**
 * @see HibernateConceptDAO#getDrugs(String,Concept,boolean,boolean,boolean,Integer,Integer)
 */
@Test
public void getDrugs_shouldReturnDistinctDrugs() {
    Concept concept1 = dao.getConcept(14);
    List<Drug> drugList = dao.getDrugs("TEST_DRUG", concept1, true, true, false, 0, 10);
    replacedert.replacedertEquals(1, drugList.size());
}

16 Source : ConceptDAOTest.java
with Apache License 2.0
from isstac

/**
 * @see {@link
 *      ConceptDAO#getConcepts(String,Locale,null,List<QConceptClreplaced;>,List<QConceptDatatype;>)}
 */
@Test
public void getConcepts_shouldNotReturnConceptsWithMatchingNamesThatAreVoided() {
    Concept concept = dao.getConcept(7);
    updateSearchIndex();
    List<Concept> concepts = dao.getConcepts("VOIDED", null, false, new ArrayList<>(), new ArrayList<>());
    replacedert.replacedertEquals(0, concepts.size());
}

16 Source : ProgramWorkflowServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.ProgramWorkflowService#getConceptStateConversion(org.openmrs.ProgramWorkflow,
 *      org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public ConceptStateConversion getConceptStateConversion(ProgramWorkflow workflow, Concept trigger) {
    return dao.getConceptStateConversion(workflow, trigger);
}

16 Source : OrderServiceImpl.java
with Apache License 2.0
from isstac

@Override
@Transactional(readOnly = true)
public List<Concept> getDrugDispensingUnits() {
    List<Concept> dispensingUnits = new ArrayList<>(getSetMembersOfConceptSetFromGP(OpenmrsConstants.GP_DRUG_DISPENSING_UNITS_CONCEPT_UUID));
    for (Concept concept : getDrugDosingUnits()) {
        if (!dispensingUnits.contains(concept)) {
            dispensingUnits.add(concept);
        }
    }
    return dispensingUnits;
}

16 Source : OrderServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.OrderService#getOrderTypeByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public OrderType getOrderTypeByConcept(Concept concept) {
    return Context.getOrderService().getOrderTypeByConceptClreplaced(concept.getConceptClreplaced());
}

16 Source : FormServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.FormService#getFieldsByConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<Field> getFieldsByConcept(Concept concept) throws APIException {
    return Context.getFormService().getFields(null, null, Collections.singleton(concept), null, null, null, null, null, null);
}

16 Source : FormServiceImpl.java
with Apache License 2.0
from isstac

/**
 * @see org.openmrs.api.FormService#getFormsContainingConcept(org.openmrs.Concept)
 */
@Override
@Transactional(readOnly = true)
public List<Form> getFormsContainingConcept(Concept concept) throws APIException {
    if (concept.getConceptId() == null) {
        return Collections.emptyList();
    }
    return dao.getFormsContainingConcept(concept);
}

15 Source : JsonKeyValuesLoaderIntegrationTest.java
with MIT License
from mekomsolutions

@Test
public void load_shouldLoadConceptList() {
    // Replay
    loader.load();
    List<Concept> concepts = getService().getConceptsFromKey("impl.purpose.concepts");
    // Verif
    replacedert.replacedertThat(concepts.size(), is(2));
    for (Concept c : concepts) {
        replacedert.replacedertNotNull(c);
    }
}

15 Source : JsonKeyValuesLoaderIntegrationTest.java
with MIT License
from mekomsolutions

@Test
public void load_shouldFetchConceptsFromAllPossibleKeys() {
    // Replay
    loader.load();
    Concept c1 = getService().getConceptFromKey("impl.purpose.concept.uuid");
    replacedert.replacedertNotNull(c1);
    Concept c2 = getService().getConceptFromKey("impl.purpose.concept.fsn");
    replacedert.replacedertEquals(c1, c2);
    Concept c3 = getService().getConceptFromKey("impl.purpose.concept.mapping");
    replacedert.replacedertEquals(c2, c3);
    replacedert.replacedertNull(getService().getConceptFromKey("__invalid_json_key__"));
    replacedert.replacedertEquals(c1, getService().getConceptFromKey("__invalid_json_key__", c1));
}

See More Examples