Issues Report
OpenMRS - Oct 26, 2017 10:42:19 PM

New issues

555

Resolved issues

76

3
New issues
12
import org.apache.commons.lang3.StringUtils;
13
import org.openmrs.Concept;
14
import org.openmrs.util.OpenmrsConstants;
Remove this unused import 'org.openmrs.util.OpenmrsConstants'.     NEW  
Useless imports should be removed
15
import org.openmrs.api.context.Context;
Remove this unused import 'org.openmrs.api.context.Context'.     NEW  
Useless imports should be removed
16

                  
17
/**
110
		this.nonCodedAllergen = nonCodedAllergen;
111
		if (StringUtils.isNotBlank(nonCodedAllergen)) {
112
			if (codedAllergen != null && !codedAllergen.getUuid().equals(getOtherNonCodedConceptUuid())) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
113
				codedAllergen = null;
114
			}
3
New issues
84
			setAttributes(new LinkedHashSet<A>());
85
		}
86
		// TODO validate
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
87
		getAttributes().add(attribute);
88
		attribute.setOwner(this);
91
	/**
92
	 * Convenience method that voids all existing attributes of the given type, and sets this new one.
93
	 * TODO fail if minOccurs &gt; 1
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
94
	 * TODO decide whether this should require maxOccurs=1
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
95
	 * @should void the attribute if an attribute with same attribute type already exists and the maxOccurs is set to 1
96
	 *
3
New issues
84
			setAttributes(new LinkedHashSet<A>());
85
		}
86
		// TODO validate
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
87
		getAttributes().add(attribute);
88
		attribute.setOwner(this);
91
	/**
92
	 * Convenience method that voids all existing attributes of the given type, and sets this new one.
93
	 * TODO fail if minOccurs &gt; 1
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
94
	 * TODO decide whether this should require maxOccurs=1
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
95
	 * @should void the attribute if an attribute with same attribute type already exists and the maxOccurs is set to 1
96
	 * @should work for attributes with datatypes whose values are stored in other tables
2
New issues
28
	public static final long serialVersionUID = 0L;
29
	
30
	private static final Log log = LogFactory.getLog(Cohort.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Remove this unused "log" private field.     NEW  
Unused private fields should be removed
31
	
32
	private Integer cohortId;
22
New issues
3 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
179
			if (answers != null) {
180
				for (ConceptAnswer ca : answers) {
181
					if (!ca.getAnswerConcept().isRetired()) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
182
						newAnswers.add(ca);
183
					}
445
	 */
446
	public ConceptName getName() {
447
		if (getNames().size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
448
			if (log.isDebugEnabled()) {
449
				log.debug("there are no names defined for: " + conceptId);
484
		}
485
		
486
		if (getSynonyms().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
487
			return getSynonyms().iterator().next();
488
		}
589
		
590
		// fail early if this concept has no names defined
591
		if (getNames().size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
592
			if (log.isDebugEnabled()) {
593
				log.debug("there are no names defined for: " + conceptId);
629
		if (fullySpecifiedName != null) {
630
			return fullySpecifiedName;
631
		} else if (getSynonyms(locale).size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
632
			return getSynonyms(locale).iterator().next();
633
		}
650
		}
651
		// fail early if this concept has no names defined
652
		if (getNames(forLocale).size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
653
			if (log.isDebugEnabled()) {
654
				log.debug("there are no names defined for concept with id: " + conceptId + " in the  locale: " + forLocale);
696
	 */
697
	public ConceptName getFullySpecifiedName(Locale locale) {
698
		if (locale != null && getNames(locale).size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
699
			//get the first fully specified name, since every concept must have a fully specified name,
700
			//then, this loop will have to return a name
731
	 */
732
	public Collection<ConceptName> getNames(Locale locale) {
733
		Collection<ConceptName> localeNames = new Vector<ConceptName>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
734
		for (ConceptName possibleName : getNames()) {
735
			if (possibleName.getLocale().equals(locale)) {
748
	 */
749
	private Collection<ConceptName> getPartiallyCompatibleNames(Locale locale) {
750
		Collection<ConceptName> localeNames = new Vector<ConceptName>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
751
		String language = locale.getLanguage();
752
		String country = locale.getCountry();
858
	public ConceptName getShortNameInLocale(Locale locale) {
859
		ConceptName bestMatch = null;
860
		if (locale != null && getShortNames().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
861
			for (ConceptName shortName : getShortNames()) {
862
				Locale nameLocale = shortName.getLocale();
883
	public Collection<ConceptName> getShortNames() {
884
		Vector<ConceptName> shortNames = new Vector<ConceptName>();
885
		if (getNames().size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
886
			if (log.isDebugEnabled()) {
887
				log.debug("The Concept with id: " + conceptId + " has no names");
967
	 */
968
	public Collection<ConceptName> getIndexTerms() {
969
		Collection<ConceptName> indexTerms = new Vector<ConceptName>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
970
		for (ConceptName name : getNames()) {
971
			if (name.isIndexTerm()) {
985
	public Collection<ConceptName> getIndexTermsForLocale(Locale locale) {
986
		
987
		Vector<ConceptName> indexTermsForLocale = new Vector<ConceptName>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
988
		if (getIndexTerms().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
989
			for (ConceptName name : getIndexTerms()) {
990
				if (name.getLocale().equals(locale)) {
1019
			if (names != null) {
1020
				for (ConceptName cn : names) {
1021
					if (!cn.isVoided()) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
1022
						ret.add(cn);
1023
					}
1051
			}
1052
			if (!names.contains(conceptName)) {
1053
				if (getNames().size() == 0
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1054
				        && !OpenmrsUtil.nullSafeEquals(conceptName.getConceptNameType(), ConceptNameType.FULLY_SPECIFIED)) {
1055
					conceptName.setConceptNameType(ConceptNameType.FULLY_SPECIFIED);
1240
	public void addDescription(ConceptDescription description) {
1241
		if (description != null && StringUtils.isNotBlank(description.getDescription())) {
1242
			if (getDescriptions() == null) {
Redundant nullcheck of org.openmrs.Concept.getDescriptions(), which is known to be non-null in org.openmrs.Concept.addDescription(ConceptDescription)     NEW  
Dodgy - Redundant nullcheck of value known to be non-null
1243
				descriptions = new HashSet<ConceptDescription>();
1244
				description.setConcept(this);
1258
	 */
1259
	public boolean removeDescription(ConceptDescription description) {
1260
		if (getDescriptions() != null) {
Redundant nullcheck of org.openmrs.Concept.getDescriptions(), which is known to be non-null in org.openmrs.Concept.removeDescription(ConceptDescription)     NEW  
Dodgy - Redundant nullcheck of value known to be non-null
1261
			return descriptions.remove(description);
1262
		} else {
1331
	 */
1332
	public Collection<ConceptName> getSynonyms() {
1333
		Collection<ConceptName> synonyms = new Vector<ConceptName>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
1334
		for (ConceptName possibleSynonym : getNames()) {
1335
			if (possibleSynonym.isSynonym()) {
1525
	 */
1526
	public Set<Locale> getAllConceptNameLocales() {
1527
		if (getNames().size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1528
			if (log.isDebugEnabled()) {
1529
				log.debug("The Concept with id: " + conceptId + " has no names");
1714
			setAttributes(new LinkedHashSet<>());
1715
		}
1716
		// TODO validate
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
1717
		getAttributes().add(attribute);
1718
		attribute.setOwner(this);
1
New issues
88
		}
89
		
90
		return getDatatype().getHl7Abbreviation().equals("ED");
Move the "ED" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
91
	}
92
	
1
New issues
11

                  
12
import org.hibernate.search.annotations.DocumentId;
13
import org.hibernate.search.annotations.Indexed;
Remove this unused import 'org.hibernate.search.annotations.Indexed'.     NEW  
Useless imports should be removed
14

                  
15
/**
2
New issues
587
	 * @see org.openmrs.Auditable#setChangedBy(org.openmrs.User)
588
	 */
589
	public void setChangedBy(User changedBy) {
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.     NEW  
Methods should not be empty
590
	}
591
	
595
	 * @see org.openmrs.Auditable#setDateChanged(java.util.Date)
596
	 */
597
	public void setDateChanged(Date dateChanged) {
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.     NEW  
Methods should not be empty
598
	}
599
}
2
New issues
267
	 * @see org.openmrs.Auditable#setChangedBy(org.openmrs.User)
268
	 */
269
	public void setChangedBy(User changedBy) {
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.     NEW  
Methods should not be empty
270
		
271
	}
276
	 * @see org.openmrs.Auditable#setDateChanged(java.util.Date)
277
	 */
278
	public void setDateChanged(Date dateChanged) {
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.     NEW  
Methods should not be empty
279
		
280
	}
1
New issues
194
	@Override
195
	public boolean isNumeric() {
196
		return getDatatype().getName().equals("Numeric");
Move the "Numeric" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
197
	}
198
	
1
New issues
1 duplicated blocks of code must be removed.     NEW
Source files should not have any duplicated blocks
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
5
New issues
15
import java.util.Deque;
16
import java.util.HashMap;
17
import java.util.HashSet;
Remove this unused import 'java.util.HashSet'.     NEW  
Useless imports should be removed
18
import java.util.Iterator;
19
import java.util.LinkedHashSet;
48
	private Patient patient;
49
	
50
	private Integer patientId;
Remove this unused "patientId" private field.     NEW  
Unused private fields should be removed
51
	
52
	private Location location;
158
			}
159
			// this should be all thats needed unless the encounter has been built by hand
160
			//if (o.isVoided() == false && o.isObsGrouping() == false)
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
161
			//	ret.add(o);
162
		}
440
        Set<EncounterProvider> activeEncounterProviders = new LinkedHashSet<EncounterProvider>();
441
        Set<EncounterProvider> providers = getEncounterProviders();
442
        if (providers != null && providers.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
443
            for (EncounterProvider provider : providers) {
444
                if (provider.isVoided() == false) {
Remove the literal "false" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
445
                    activeEncounterProviders.add(provider);
446
                }
1
New issues
122
	 */
123
	public void setAttributeName(String attributeName) {
124
		// this.dirty = true;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
125
		this.attributeName = attributeName;
126
	}
2
New issues
10
package org.openmrs;
11

                  
12
import org.apache.commons.collections.CollectionUtils;
Remove this unused import 'org.apache.commons.collections.CollectionUtils'.     NEW  
Useless imports should be removed
13
import org.apache.commons.lang.StringUtils;
14
import org.apache.commons.logging.Log;
830
	 */
831
	public boolean isComplex() {
832
		//		if (getValueComplex() != null) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
833
		//			return true;
834
		//		}
1
New issues
14
 * system and descriptive data such as data types &mdash; a relationship type or encounter type.
15
 * Metadata are generally referenced by clinical data but don't represent patient-specific data
16
 * themselves. OpenMRS objects that represent metadata should implement this interface. TODO:
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
17
 * Support localized names and descriptions
18
 * 
6
New issues
57
	}
58
	
59
	private static final Log log = LogFactory.getLog(Order.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Remove this unused "log" private field.     NEW  
Unused private fields should be removed
60
	
61
	private Integer orderId;
426
		}
427
		if (checkDate == null) {
428
			checkDate = new Date();
Introduce a new variable instead of reusing the parameter "checkDate".     NEW  
Method parameters, caught exceptions and foreach variables should not be reassigned
429
		}
430
		
464
		}
465
		if (checkDate == null) {
466
			checkDate = new Date();
Introduce a new variable instead of reusing the parameter "checkDate".     NEW  
Method parameters, caught exceptions and foreach variables should not be reassigned
467
		}
468
		if (getEffectiveStartDate() == null) {
497
		}
498
		if (checkDate == null) {
499
			checkDate = new Date();
Introduce a new variable instead of reusing the parameter "checkDate".     NEW  
Method parameters, caught exceptions and foreach variables should not be reassigned
500
		}
501
		if (!isActivated(checkDate) || dateStopped == null) {
539
		}
540
		if (checkDate == null) {
541
			checkDate = new Date();
Introduce a new variable instead of reusing the parameter "checkDate".     NEW  
Method parameters, caught exceptions and foreach variables should not be reassigned
542
		}
543
		if (!isActivated(checkDate)) {
8
New issues
17
import java.util.Vector;
18

                  
19
import org.openmrs.api.APIException;
Remove this unused import 'org.openmrs.api.APIException'.     NEW  
Useless imports should be removed
20

                  
21
/**
48
	 * as pointers, each individual element is not copied. <br>
49
	 * <br>
50
	 * TODO Should the patient specific attributes be copied? (like identifiers)
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
51
	 * 
52
	 * @param person the person object to copy onto a new Patient
215
	 * @return Returns the "preferred" patient identifier.
216
	 */
217
	public PatientIdentifier getPatientIdentifier() {
The Cyclomatic Complexity of this method "getPatientIdentifier" is 11 which is greater than 10 authorized.     NEW  
Methods should not be too complex
218
		// normally the DAO layer returns these in the correct order, i.e. preferred and non-voided first, but it's possible that someone
219
		// has fetched a Patient, changed their identifiers around, and then calls this method, so we have to be careful.
220
		if (getIdentifiers() != null && getIdentifiers().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
221
			for (PatientIdentifier id : getIdentifiers()) {
222
				if (id.isPreferred() && !id.isVoided()) {
243
	 */
244
	public PatientIdentifier getPatientIdentifier(PatientIdentifierType pit) {
245
		if (getIdentifiers() != null && getIdentifiers().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
246
			for (PatientIdentifier id : getIdentifiers()) {
247
				if (id.isPreferred() && !id.isVoided() && pit.equals(id.getIdentifierType())) {
266
	 */
267
	public PatientIdentifier getPatientIdentifier(Integer identifierTypeId) {
268
		if (getIdentifiers() != null && getIdentifiers().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
269
			for (PatientIdentifier id : getIdentifiers()) {
270
				if (id.isPreferred() && !id.isVoided()
291
	 */
292
	public PatientIdentifier getPatientIdentifier(String identifierTypeName) {
293
		if (getIdentifiers() != null && getIdentifiers().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
294
			for (PatientIdentifier id : getIdentifiers()) {
295
				if (id.isPreferred() && !id.isVoided() && identifierTypeName.equals(id.getIdentifierType().getName())) {
321
			for (PatientIdentifier pi : getIdentifiers()) {
322
				if (!pi.isVoided()) {
323
					if (pi.isPreferred()) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
324
						ids.add(pi);
325
					} else {
1
New issues
206
	 */
207
	@SuppressWarnings("squid:S1210")
208
	public int compareTo(PatientIdentifier other) {
Add the missing @Deprecated annotation.     NEW  
Deprecated elements should have both the annotation and the Javadoc tag
209
		DefaultComparator piDefaultComparator = new DefaultComparator();
210
		return piDefaultComparator.compare(this, other);
2
New issues
67
	private String formatDescription;
68
	
69
	private Boolean checkDigit = Boolean.FALSE;
Remove this unused "checkDigit" private field.     NEW  
Unused private fields should be removed
70
	
71
	private String validator;
188
	
189
	/**
190
	 * TODO: make this return a more debug-worth string instead of just the name. Check the webapp
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
191
	 * to make sure it is not depending on this
192
	 * 
1
New issues
211
		PatientState last = null;
212
		PatientState nextToLast = null;
213
		if (states.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
214
			last = states.get(states.size() - 1);
215
		}
6
New issues
13 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
203
	@JsonIgnore
204
	public Boolean isBirthdateEstimated() {
205
		// if (this.birthdateEstimated == null) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
206
		// return new Boolean(false);
207
		// }
460
	public void removeAttribute(PersonAttribute attribute) {
461
		if (attributes != null) {
462
			if (attributes.remove(attribute)) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
463
				attributeMap = null;
464
				allAttributeMap = null;
734
		// normally the DAO layer returns these in the correct order, i.e. preferred and non-voided first, but it's possible that someone
735
		// has fetched a Person, changed their names around, and then calls this method, so we have to be careful.
736
		if (getNames() != null && getNames().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
737
			for (PersonName name : getNames()) {
738
				if (name.isPreferred() && !name.isVoided()) {
816
		// normally the DAO layer returns these in the correct order, i.e. preferred and non-voided first, but it's possible that someone
817
		// has fetched a Person, changed their addresses around, and then calls this method, so we have to be careful.
818
		if (getAddresses() != null && getAddresses().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
819
			for (PersonAddress addr : getAddresses()) {
820
				if (addr.isPreferred() && !addr.isVoided()) {
1019
	 */
1020
	@SuppressWarnings("unused")
1021
	private void setPatient(boolean isPatient) {
Private method 'setPatient' is never used.     NEW  
Unused private method should be removed
1022
		this.isPatient = isPatient;
1023
	}
2
New issues
183
	 */
184
	public boolean inheritsRoles() {
185
		return getInheritedRoles() != null && getInheritedRoles().size() > 0;
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
186
	}
187
	
275
	 */
276
	public boolean hasChildRoles() {
277
		return getChildRoles() != null && getChildRoles().size() > 0;
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
278
	}
279
	
1
New issues
138
	public boolean hasRole(String r, boolean ignoreSuperUser) {
139
		if (!ignoreSuperUser) {
140
			if (isSuperUser()) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
141
				return true;
142
			}
1
New issues
4 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
1
New issues
45
			return !matchOpenmrsProfileAttributes(openmrsProfileAttributes);
46
		} else {
47
			return false; //do not exclude
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
48
		}
49
	}
1
New issues
133
					}
134
				}
135
				log.debug(String.format(
Format string should use %n rather than \n in org.openmrs.aop.LoggingAdvice.invoke(MethodInvocation)     NEW  
Format string should use %n rather than \n
136
				    "An error occurred while executing this method.\nCurrent user: %s\nError message: %s", username, e
137
				            .getMessage()), e);
1
New issues
292
	 * AdministrationService).
293
	 * 
294
	 * @return list of allowed presentation locales TODO change this return type to list?
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
295
	 * @should return at least one locale if no locales defined in database yet
296
	 * @should not return more locales than message source service locales
1
New issues
44
	/**
45
	 * Gets the default handler for a {@link CustomDatatype}, and sets its configuration
46
	 * TODO probably remove the config argument since it doesn't make sense to let people provide handlerConfig to the default handler. If we remove this argument, we also need to change BaseAttributeTypeValidator  
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
47
	 * 
48
	 * @param datatype
1
New issues
39
	public void setGlobalPropertyListeners(List<GlobalPropertyListener> globalPropertyListeners) {
40
		if (log.isDebugEnabled()) {
41
			StringBuffer sb = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
42
			for (GlobalPropertyListener gpl : globalPropertyListeners) {
43
				if (sb.length() > 0) {
1
New issues
14
/**
15
 * This interface allows code to be run when global properties are created, edited, or deleted. <br>
16
 * TODO: Make sure listeners are notified if a global property's name is changed.
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
17
 * 
18
 * @see AdministrationService#addGlobalPropertyListener(GlobalPropertyListener)
1
New issues
368
	/**
369
	 * Get a complex observation. If obs.isComplex() is true, then returns an Obs with its
370
	 * ComplexData. Otherwise returns a simple Obs. TODO: Possibly remove this method. It is
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
371
	 * confusing because you may have a complexObs, but not want the complexData attached at the
372
	 * time. Nevertheless, you may think that this method is necessary to use, when you could just
2
New issues
487
	@Authorized({ PrivilegeConstants.ADD_ORDERS, PrivilegeConstants.EDIT_ORDERS })
488
	public Order discontinueOrder(Order orderToDiscontinue, Concept reasonCoded, Date discontinueDate, Provider orderer,
489
	        Encounter encounter) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
490
	
491
	/**
510
	@Authorized({ PrivilegeConstants.ADD_ORDERS, PrivilegeConstants.EDIT_ORDERS })
511
	public Order discontinueOrder(Order orderToDiscontinue, String reasonNonCoded, Date discontinueDate, Provider orderer,
512
	        Encounter encounter) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
513
	
514
	/**
2
New issues
564
	 * Convenience method to establish that a patient has died. In addition to exiting the patient
565
	 * from care (see above), this method will also set the appropriate patient characteristics to
566
	 * indicate that they have died, when they died, etc. TODO Keep this in the PatientService? Or
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
567
	 * move to appropriate service
568
	 * 
580
	/**
581
	 * Convenience method that saves the Obs that indicates when and why the patient died (including
582
	 * any "other" reason there might be) TODO keep this in the PatientService?
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
583
	 * 
584
	 * @param patient - the patient who has died
1
New issues
457
	
458
	/**
459
	 * TODO: refactor?
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
460
	 * 
461
	 * @param cohort
1
New issues
748
	public static void closeSessionWithCurrentUser() {
749
		getContextDAO().closeSession();
750
		;
Remove this empty statement.     NEW  
Empty statements should be removed
751
	}
752
	
1
New issues
118
		
119
		// quick check to make sure we're only being called by ourselves
120
		//Class<?> callerClass = Reflection.getCallerClass(0);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
121
		Class<?> callerClass = new OpenmrsSecurityManager().getCallerClass(0);
122
		if (!TimerSchedulerTask.class.isAssignableFrom(callerClass)) {
1
New issues
56
	 * @throws DAOException
57
	 */
58
	public List<Cohort> getCohortsContainingPatientId(Integer patientId) throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
59
	
60
	/**
7
New issues
28
	 * @throws DAOException
29
	 */
30
	public List<Note> getNotes() throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
31
	
32
	/**
36
	 * @throws DAOException
37
	 */
38
	public void createNote(Note note) throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
39
	
40
	/**
45
	 * @throws DAOException
46
	 */
47
	public Note getNote(Integer noteId) throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
48
	
49
	/**
53
	 * @throws DAOException
54
	 */
55
	public void updateNote(Note note) throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
56
	
57
	/**
58
	 * TODO: Couldn't find a voidNote method Delete note from database. This <b>should not be
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
59
	 * called</b> except for testing and administration purposes. Use the void method instead.
60
	 * 
62
	 * @throws DAOException
63
	 */
64
	public void deleteNote(Note note) throws DAOException;
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
65
	
66
	/**
69
	 * @throws APIException
70
	 */
71
	public Note voidNote(Note note, String reason) throws APIException;
Remove the declaration of thrown exception 'org.openmrs.api.APIException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
72
}
1
New issues
119
		
120
		for (String property : propertyValues.keySet()) {
121
			if (changePropertyValue(currentState, propertyNames, property, propertyValues.get(property), setNullOnly)) {
org.openmrs.api.db.hibernate.AuditableInterceptor.changeProperties(Object[], String[], boolean, Map, Boolean) makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
122
				objectWasChanged = true;
123
			}
1
New issues
116
	
117
	public Boolean isTransient(Object entity) {
118
		Boolean returnValue = null; // by default let hibernate figure it out
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
119
		
120
		for (Interceptor i : interceptors) {
1
New issues
35
import org.springframework.context.ApplicationContext;
36
import org.springframework.context.ApplicationContextAware;
37
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
Remove this unused import 'org.springframework.orm.hibernate3.LocalSessionFactoryBean'.     NEW  
Useless imports should be removed
38
import org.springframework.validation.Errors;
39
import org.springframework.validation.Validator;
9
New issues
105
		// and re-fetch it as a ConceptComplex
106
		if (obj != null && !obj.getClass().equals(ConceptComplex.class)) {
107
			sessionFactory.getCurrentSession().evict(obj); // remove from cache
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
108
			// session.get() did not work here, we need to perform a query to get a ConceptComplex
109
			Query query = sessionFactory.getCurrentSession().createQuery("from ConceptComplex where conceptId = :conceptId")
506
		// and re-fetch it as a ConceptNumeric
507
		if (obj != null && !obj.getClass().equals(ConceptNumeric.class)) {
508
			sessionFactory.getCurrentSession().evict(obj); // remove from cache
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
509
			// session.get() did not work here, we need to perform a query to get a ConceptNumeric
510
			Query query = sessionFactory.getCurrentSession().createQuery("from ConceptNumeric where conceptId = :conceptId")
665
		    Restrictions.lt("conceptId", i)).addOrder(Order.desc("conceptId")).setFetchSize(1).list();
666
		
667
		if (concepts.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
668
			return null;
669
		}
681
		    Restrictions.gt("conceptId", i)).addOrder(Order.asc("conceptId")).setMaxResults(1).list();
682
		
683
		if (concepts.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
684
			return null;
685
		}
841
		    Restrictions.eq("tag", name));
842
		
843
		if (crit.list().size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
844
			return null;
845
		}
947
		 */
948
		public boolean hasNext() {
949
			return (nextConcept != null);
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
950
		}
951
		
1512
		criteria.add(Restrictions.eq("conceptSource", conceptSource));
1513
		List terms = criteria.list();
1514
		if (terms.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1515
			return null;
1516
		} else if (terms.size() > 1) {
1532
		criteria.add(Restrictions.eq("conceptSource", conceptSource));
1533
		List terms = criteria.list();
1534
		if (terms.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1535
			return null;
1536
		} else if (terms.size() > 1) {
1847
		
1848
		// match with any of the supplied collection or order of preference of conceptMapTypes
1849
		if (withAnyOfTheseTypesOrOrderOfPreference.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1850
			for (ConceptMapType conceptMapType : withAnyOfTheseTypesOrOrderOfPreference) {
1851
				criteria.add(Restrictions.eq("map.conceptMapType", conceptMapType));
4
New issues
116
			String lockoutTimeString = candidateUser.getUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, null);
117
			Long lockoutTime = null;
118
			if (lockoutTimeString != null && !lockoutTimeString.equals("0")) {
Move the "0" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
119
				try {
120
					// putting this in a try/catch in case the admin decided to put junk into the property
442
			while (results.next()) {
443
				index++;
444
				session.index(results.get(0)); //index each element
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
445
				if (index % 1000 == 0) {
446
					session.flushToIndexes(); //apply changes to indexes
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
447
					session.clear(); //free memory since the queue is processed
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
448
				}
449
			}
5
New issues
136
			);
137
		}
138
		if (searchCriteria.getEnteredViaForms() != null && searchCriteria.getEnteredViaForms().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
139
			crit.add(Restrictions.in("form", searchCriteria.getEnteredViaForms()));
140
		}
141
		if (searchCriteria.getEncounterTypes() != null && searchCriteria.getEncounterTypes().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
142
			crit.add(Restrictions.in("encounterType", searchCriteria.getEncounterTypes()));
143
		}
144
		if (searchCriteria.getProviders() != null && searchCriteria.getProviders().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
145
			crit.createAlias("encounterProviders", "ep");
146
			crit.add(Restrictions.in("ep.provider", searchCriteria.getProviders()));
147
		}
148
		if (searchCriteria.getVisitTypes() != null && searchCriteria.getVisitTypes().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
149
			crit.createAlias("visit", "v");
150
			crit.add(Restrictions.in("v.visitType", searchCriteria.getVisitTypes()));
151
		}
152
		if (searchCriteria.getVisits() != null && searchCriteria.getVisits().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
153
			crit.add(Restrictions.in("visit", searchCriteria.getVisits()));
154
		}
3
New issues
202
		String err = "FormField warning.  No FormField matching concept '" + concept + "' for form '" + form + "'";
203
		
204
		if (formFields.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
205
			log.debug(err);
206
			return null;
215
		// if we ended up removing all of the formfields, check to see if we're
216
		// in a "force" situation
217
		if (formFields.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
218
			if (!force) {
219
				return backupPlan;
222
				return null;
223
			}
224
		} else { // if formFields.size() is still greater than 0
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
225
			FormField ff = (FormField) formFields.get(0);
226
			return ff;
5
New issues
10
package org.openmrs.api.db.hibernate;
11

                  
12
import java.util.ArrayList;
Remove this unused import 'java.util.ArrayList'.     NEW  
Useless imports should be removed
13
import java.util.List;
14

                  
23
public class HibernateNoteDAO implements NoteDAO {
24
	
25
	protected final static Log log = LogFactory.getLog(HibernateNoteDAO.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
26
	
27
	/**
69
	}
70
	
71
	public void deleteNote(Note note) throws DAOException {
Remove the declaration of thrown exception 'org.openmrs.api.db.DAOException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
72
		log.debug("Deleting existing note");
73
		sessionFactory.getCurrentSession().delete(note);
77
	 * @see org.openmrs.api.db.NoteDAO#voidNote(org.openmrs.notification.Note, java.lang.String)
78
	 */
79
	public Note voidNote(Note note, String reason) throws APIException {
Remove the declaration of thrown exception 'org.openmrs.api.APIException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
80
		log.debug("voiding note because " + reason);
81
		sessionFactory.getCurrentSession().save(note);
1
New issues
242
		if (personTypes.contains(PERSON_TYPE.PERSON)) {
243
			// all observations are already on person's.  Limit to non-patient and non-users here?
244
			//criteria.createAlias("Person", "person");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
245
			//criteria.add(Restrictions.eqProperty("obs.person.personId", "person.personId"));
246
		}
9
New issues
123
		}
124
		
125
		if (patients.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
126
			crit.add(Restrictions.in("patient", patients));
127
		}
128
		
129
		if (concepts.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
130
			crit.add(Restrictions.in("concept", concepts));
131
		}
134
		// algorithm dependent  
135
		
136
		if (orderers.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
137
			crit.add(Restrictions.in("orderer", orderers));
138
		}
139
		
140
		if (encounters.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
141
			crit.add(Restrictions.in("encounter", encounters));
142
		}
327
			criteria.add(Restrictions.eq("careSetting", careSetting));
328
		}
329
		if (orderTypes != null && orderTypes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
330
			criteria.add(Restrictions.in("orderType", orderTypes));
331
		}
476
			Class<?> entityClass = classMetadata.getMappedClass();
477
			if (Order.class.equals(entityClass)) {
478
				continue; //ignore the org.openmrs.Order class itself
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
479
			}
480
			
481
			if (!Order.class.isAssignableFrom(entityClass)) {
482
				continue; //not a sub class of Order
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
483
			}
484
			
489
					criteria.add(Restrictions.eq(name, orderFrequency));
490
					criteria.setMaxResults(1);
491
					if (criteria.list().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
492
						return true;
493
					}
580
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Order.class);
581
		criteria.add(Restrictions.eq("orderType", orderType));
582
		return criteria.list().size() > 0;
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
583
	}
584
}
1
New issues
16
import org.hibernate.SessionFactory;
17
import org.hibernate.criterion.Restrictions;
18
import org.openmrs.ConceptDescription;
Remove this unused import 'org.openmrs.ConceptDescription'.     NEW  
Useless imports should be removed
19
import org.openmrs.OrderSet;
20
import org.openmrs.OrderSetMember;
23
New issues
27
import org.apache.commons.logging.LogFactory;
28
import org.hibernate.Criteria;
29
import org.hibernate.HibernateException;
Remove this unused import 'org.hibernate.HibernateException'.     NEW  
Useless imports should be removed
30
import org.hibernate.Query;
31
import org.hibernate.SQLQuery;
104
			// and Persons are the same objects.  So it sees a Person object in the
105
			// cache and claims it is a duplicate of this Patient object.
106
			//patient = (Patient) sessionFactory.getCurrentSession().merge(patient);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
107
			sessionFactory.getCurrentSession().saveOrUpdate(patient);
108
			
131
		
132
		if (stubInsertNeeded) {
133
			if (patient.getCreator() == null) { //If not yet persisted
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
134
				patient.setCreator(Context.getAuthenticatedUser());
135
			}
136
			if (patient.getDateCreated() == null) { //If not yet persisted
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
137
				patient.setDateCreated(new Date());
138
			}
161
	 */
162
	@Override
163
	public List<Patient> getPatients(String query, boolean includeVoided, Integer start, Integer length) throws DAOException {
The Cyclomatic Complexity of this method "getPatients" is 13 which is greater than 10 authorized.     NEW  
Methods should not be too complex
164
		if (StringUtils.isBlank(query) || (length != null && length < 1)) {
165
			return Collections.emptyList();
305
		}
306
		
307
		// TODO add junit test for getting by identifier type
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
308
		if (patientIdentifierTypes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
309
			criteria.add(Restrictions.in("identifierType", patientIdentifierTypes));
310
		}
311
		
312
		if (locations.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
313
			criteria.add(Restrictions.in("location", locations));
314
		}
315
		
316
		// TODO add junit test for getting by patients
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
317
		if (patients.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
318
			criteria.add(Restrictions.in("patient", patients));
319
		}
364
			criteria.add(Restrictions.eq("retired", false));
365
		} else {
366
			criteria.addOrder(Order.asc("retired")); //retired last
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
367
		}
368
		
369
		criteria.addOrder(Order.desc("required")); //required first
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
370
		criteria.addOrder(Order.asc("name"));
371
		criteria.addOrder(Order.asc("patientIdentifierTypeId"));
414
		criteria.add(Restrictions.eq("retired", false));
415
		
416
		criteria.addOrder(Order.desc("required")); //required first
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
417
		criteria.addOrder(Order.asc("name"));
418
		criteria.addOrder(Order.asc("patientIdentifierTypeId"));
429
		List<Integer> patientIds = new Vector<Integer>();
430

                  
431
		if (attributes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
432

                  
433
			String sqlString = getDuplicatePatientsSQLString(attributes);
436
				SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(sqlString);
437
				patientIds = sqlquery.list();
438
				if (patientIds.size() >= 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
439
					Query query = sessionFactory.getCurrentSession().createQuery(
440
							"from Patient p1 where p1.patientId in (:ids)");
493
			if (patientFieldNames.contains(attribute)) {
494

                  
495
				AbstractEntityPersister aep = ((AbstractEntityPersister) sessionFactory.getClassMetadata(Patient.class));
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
496
				String[] properties = aep.getPropertyColumnNames(attribute);
497
				if (properties.length >= 1) {
498
					attribute = properties[0];
499
				}
500
				whereConditions.add(" t1." + attribute + " = t5." + attribute);
Define a constant instead of duplicating this literal " = t5." 4 times.     NEW  
String literals should not be duplicated
501
				innerFields.add("p1." + attribute);
502
			} else if (personFieldNames.contains(attribute)) {
506
				}
507

                  
508
				AbstractEntityPersister aep = ((AbstractEntityPersister) sessionFactory.getClassMetadata(Person.class));
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
509
				if (aep != null) {
510
					String[] properties = aep.getPropertyColumnNames(attribute);
523

                  
524
				//Since we are firing a native query get the actual table column name from the field name of the entity
525
				AbstractEntityPersister aep = ((AbstractEntityPersister) sessionFactory
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
526
						.getClassMetadata(PersonName.class));
527
				if (aep != null) {
541
				}
542

                  
543
				AbstractEntityPersister aep = ((AbstractEntityPersister) sessionFactory
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
544
						.getClassMetadata(PatientIdentifier.class));
545
				if (aep != null) {
557
			}
558
		}
559
		if(innerFields.size() > 0 || whereConditions.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
560
			String innerFieldsJoined = StringUtils.join(innerFields, ", ");
561
			String whereFieldsJoined = StringUtils.join(whereConditions, " and ");
659
			query.setInteger("locationId", patientIdentifier.getLocation().getLocationId());
660
		}
661
		return !query.uniqueResult().toString().equals("0");
Move the "0" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
662
	}
663
	
4
New issues
158
				q.append("  when soundex(pname.familyName2) = soundex(:n").append(i + 1).append(") then 1");
159
			}
160
			q.append("  else 0").append(" end").append(") >= ").append((int) (names.length * .75)); // if most of the names have at least a hit somewhere
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
161
		}
162
		
240
		PersonSearchCriteria personSearchCriteria = new PersonSearchCriteria();
241
		
242
		searchString = searchString.replace(", ", " ");
Introduce a new variable instead of reusing the parameter "searchString".     NEW  
Method parameters, caught exceptions and foreach variables should not be reassigned
243
		String[] values = searchString.split(" ");
244
		
247
		personSearchCriteria.addAliasForName(criteria);
248
		personSearchCriteria.addAliasForAttribute(criteria);
249
		if (voided == null || voided == false) {
Remove the literal "false" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
250
			criteria.add(Restrictions.eq("personVoided", false));
251
		}
269
		criteria.setMaxResults(getMaximumSearchResults());
270
		
271
		// TODO - remove
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
272
		log.debug(criteria.toString());
273
		
1
New issues
227
			serializedObject.setName(metaObj.getName());
228
			serializedObject.setDescription(metaObj.getDescription());
229
			serializedObject.setRetired(metaObj.isRetired() == Boolean.TRUE);
Suspicious comparison of Boolean references in org.openmrs.api.db.hibernate.HibernateSerializedObjectDAO.saveObject(OpenmrsObject, OpenmrsSerializer)     NEW  
Correctness - Suspicious reference comparison of Boolean values
230
			serializedObject.setRetiredBy(metaObj.getRetiredBy());
231
			serializedObject.setDateRetired(metaObj.getDateRetired());
3
New issues
99
		List<User> users = query.list();
100
		
101
		if (users == null || users.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
102
			log.warn("request for username '" + username + "' not found");
103
			return null;
573
		}
574
		
575
		if (criteria.size() > 0 || searchOnRoles) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
576
			hql.append("where ");
577
		}
585
		//Match against the specified roles
586
		if (searchOnRoles) {
587
			if (criteria.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
588
				hql.append(" and ");
589
			}
1
New issues
309
		}
310
		
311
		// TODO add a junit test for patientIdentifierType restrictions	
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
312
		
313
		// do the type restriction
3
New issues
41
		
42
		// address collection
43
		if (person.getAddresses() != null && person.getAddresses().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
44
			for (PersonAddress pAddress : person.getAddresses()) {
45
				pAddress.setPerson(person);
48
		
49
		// name collection
50
		if (person.getNames() != null && person.getNames().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
51
			for (PersonName pName : person.getNames()) {
52
				pName.setPerson(person);
55
		
56
		// attribute collection
57
		if (person.getAttributes() != null && person.getAttributes().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
58
			for (PersonAttribute pAttr : person.getAttributes()) {
59
				pAttr.setPerson(person);
2
New issues
267
				}
268
			} else if (gp.getProperty().equals(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE)) {
269
				if (gp.getPropertyValue() != null) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
270
					List<Locale> localeList = getAllowedLocales();
271
					
272
					if (!localeList.contains(LocaleUtility.fromSpecification(gp.getPropertyValue().trim()))) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
273
						String value = gp.getPropertyValue();
274
						gp.setPropertyValue(LocaleUtility.getDefaultLocale().toString());
5
New issues
148
						}
149
						catch (IllegalAccessException e) {
150
							log.error("Error generated", e);
Define a constant instead of duplicating this literal "Error generated" 6 times.     NEW  
String literals should not be duplicated
151
						}
152
						catch (InvocationTargetException e) {
225
		
226
		// force isSet when concept has members
227
		if (!concept.isSet() && (concept.getSetMembers().size() > 0)) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
228
                    concept.setSet(true);
229
		}
230

                  
231
		Concept conceptToReturn = dao.saveConcept(concept);
Immediately return this expression instead of assigning it to the temporary variable "conceptToReturn".     NEW  
Local Variables should not be declared and then immediately returned or thrown
232
		
233
		return conceptToReturn;
455
				log.warn("more than one drug name returned with name:" + drugNameOrId);
456
			}
457
			if (drugs.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
458
				return null;
459
			}
1049
		List<Concept> concepts = Context.getConceptService().getConceptsByMapping(code, sourceName, includeRetired);
1050
		
1051
		if (concepts.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1052
			return null;
1053
		}
1
New issues
191
			for (Class dt : getAllDatatypeClasses()) {
192
				List<Class<? extends CustomDatatypeHandler>> handlerClasses = getHandlerClasses(dt);
193
				if (handlerClasses == null || handlerClasses.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
194
					prioritizedHandlerClasses.put(dt, null);
195
				} else {
3
New issues
64
public class EncounterServiceImpl extends BaseOpenmrsService implements EncounterService {
65
	
66
	// private Log log = LogFactory.getLog(this.getClass());
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
67
	
68
	private EncounterDAO dao;
882
		String locked = Context.getAdministrationService().getGlobalProperty(
883
		    OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_TYPES_LOCKED, "false");
884
		if (locked.toLowerCase().equals("true")) {
Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.     NEW  
Case insensitive string comparisons should be made without intermediate upper or lower casing
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
885
			throw new EncounterTypeLockedException();
886
		}
6
New issues
102
	public Form duplicateForm(Form form) throws APIException {
103
		// Map of /Old FormFieldId/ to /New FormField Object/
104
		//TreeMap<Integer, FormField> formFieldMap = new TreeMap<Integer, FormField>();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
105
		//formFieldMap.put(null, null); //for parentless formFields
106
		checkIfFormsAreLocked();
109
		
110
		for (FormField formField : form.getFormFields()) {
111
			//formFieldMap.put(formField.getFormFieldId(), formField);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
112
			formField.setUuid(null);
113
			formField.setFormFieldId(null);
114
			//formField.setParent(formFieldMap.get(formField.getParent().getFormFieldId()));
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
115
		}
116
		// this is required because Hibernate would recognize the original collection
343
	public Form getForm(String name) throws APIException {
344
		List<Form> forms = dao.getFormsByName(name);
345
		if (forms == null || forms.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
346
			return null;
347
		} else {
785
		String locked = Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_FORMS_LOCKED,
786
		    "false");
787
		if (locked.toLowerCase().equals("true")) {
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.     NEW  
Case insensitive string comparisons should be made without intermediate upper or lower casing
788
			throw new FormsLockedException();
789
		}
2
New issues
131
		}
132
		
133
		// TODO Figure out if we should/could throw an exception if there's  
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
134
		// no location to fall back on.
135
		//if (location == null) { 
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
136
		//	throw new APIException("Default location does not exist");
137
		//}
2
New issues
411
		List<Obs> returnList = new Vector<Obs>();
412
		
413
		if (encounters.size() > 0 || persons.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
414
			returnList = Context.getObsService().getObservations(persons, encounters, null, null, null, null, null, null,
415
			    null, null, null, false);
4
New issues
279
				int minutes = cal.get(Calendar.MINUTE);
280
				int seconds = cal.get(Calendar.SECOND);
281
				int milliseconds = cal.get(Calendar.MILLISECOND);
Remove this unused "milliseconds" local variable.     NEW  
Unused local variables should be removed
Dead store to milliseconds in org.openmrs.api.impl.OrderServiceImpl.saveOrderInternal(Order, OrderContext)     NEW  
Dodgy - Dead store to local variable
282
				//roll autoExpireDate to end of day (23:59:59) if no time portion is specified
283
				if (hours == 0 && minutes == 0 && seconds == 0) {
285
					cal.set(Calendar.MINUTE, 59);
286
					cal.set(Calendar.SECOND, 59);
287
					cal.set(Calendar.MILLISECOND, 0); // the OpenMRS database is only precise to the second
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
288
					order.setAutoExpireDate(cal.getTime());
289
				}
762
	public OrderFrequency saveOrderFrequency(OrderFrequency orderFrequency) throws APIException {
763
		if (orderFrequency.getOrderFrequencyId() != null) {
764
			if (dao.isOrderFrequencyInUse(orderFrequency)) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
765
				throw new APIException("Order.frequency.cannot.edit");
766
			}
3
New issues
11

                  
12
import org.apache.commons.collections.CollectionUtils;
13
import org.openmrs.ConceptDescription;
Remove this unused import 'org.openmrs.ConceptDescription'.     NEW  
Useless imports should be removed
14
import org.openmrs.OrderSet;
15
import org.openmrs.OrderSetMember;
16
import org.openmrs.annotation.Authorized;
Remove this unused import 'org.openmrs.annotation.Authorized'.     NEW  
Useless imports should be removed
17
import org.openmrs.api.APIException;
18
import org.openmrs.api.OrderSetService;
19
import org.openmrs.api.context.Context;
20
import org.openmrs.api.db.OrderSetDAO;
21
import org.openmrs.util.PrivilegeConstants;
Remove this unused import 'org.openmrs.util.PrivilegeConstants'.     NEW  
Useless imports should be removed
22
import org.springframework.transaction.annotation.Transactional;
23
import org.springframework.util.StringUtils;
17
New issues
116
	 * @see org.openmrs.api.PatientService#savePatient(org.openmrs.Patient)
117
	 */
118
	public Patient savePatient(Patient patient) throws APIException {
The Cyclomatic Complexity of this method "savePatient" is 27 which is greater than 10 authorized.     NEW  
Methods should not be too complex
119
		if (patient.getPatientId() == null) {
120
			Context.requirePrivilege(PrivilegeConstants.ADD_PATIENTS);
256
	 */
257
	@Transactional(readOnly = true)
258
	public void checkPatientIdentifiers(Patient patient) throws PatientIdentifierException {
The Cyclomatic Complexity of this method "checkPatientIdentifiers" is 17 which is greater than 10 authorized.     NEW  
Methods should not be too complex
259
		// check patient has at least one identifier
260
		if (!patient.isVoided() && patient.getActiveIdentifiers().size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
261
			throw new InsufficientIdentifiersException("At least one nonvoided Patient Identifier is required");
262
		}
263
		
264
		List<PatientIdentifier> identifiers = new Vector<PatientIdentifier>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
265
		identifiers.addAll(patient.getIdentifiers());
266
		List<String> identifiersUsed = new Vector<String>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
267
		List<PatientIdentifierType> requiredTypes = Context.getPatientService().getPatientIdentifierTypes(null, null, true,
268
		    null);
294
			}
295
			
296
			// TODO: check patient has at least one "sufficient" identifier
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
297
			// TODO: what makes a patient identifier unique ... can you have the
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
298
			// 		 same identifier number at different locations?  if so, then this
299
			// 		 check duplicate algorithm does not handle this case
310
		}
311
		
312
		if (requiredTypes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
313
			String missingNames = "";
314
			for (PatientIdentifierType pit : requiredTypes) {
383
	
384
	/**
385
	 * TODO: Add changedBy and DateChanged columns to table patient_identifier_type
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
386
	 * 
387
	 * @see org.openmrs.api.PatientService#savePatientIdentifierType(org.openmrs.PatientIdentifierType)
433
		List<PatientIdentifierType> types = getPatientIdentifierTypes(name, null, null, null);
434
		
435
		if (types.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
436
			return types.get(0);
437
		}
511
	public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException {
512
		
513
		if (attributes == null || attributes.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
514
			throw new APIException("Patient.no.attribute", (Object[]) null);
515
		}
869
		}
870
		/*
871
		 * if (preferred.getRace() == null || preferred.getRace().equals(""))
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
872
		 * preferred.setRace(notPreferred.getRace());
873
		 */
1057
	 */
1058
	public void processDeath(Patient patient, Date dateDied, Concept causeOfDeath, String otherReason) throws APIException {
1059
		//SQLStateConverter s = null;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
1060
		
1061
		if (patient != null && dateDied != null && causeOfDeath != null) {
1294
		
1295
		try {
1296
			return getIdentifierValidator(((Class<IdentifierValidator>) Context.loadClass(pivClassName)));
Remove those useless parentheses.     NEW  
Useless parentheses around expressions should be removed to prevent any misunderstanding
1297
		}
1298
		catch (ClassNotFoundException e) {
1390
		Allergies allergies = new Allergies();
1391
		List<Allergy> allergyList = dao.getAllergies(patient);
1392
		if (allergyList.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1393
			allergies.addAll(allergyList);
1394
		} else {
1596
		String locked = Context.getAdministrationService().getGlobalProperty(
1597
		    OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_IDENTIFIER_TYPES_LOCKED, "false");
1598
		if (locked.toLowerCase().equals("true")) {
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.     NEW  
Case insensitive string comparisons should be made without intermediate upper or lower casing
1599
			throw new PatientIdentifierTypeLockedException();
1600
		}
13
New issues
27 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
113
		List<PersonAttributeType> types = Context.getPersonService().getPersonAttributeTypes(typeName, null, null, null);
114
		
115
		if (types.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
116
			return null;
117
		} else {
135
		if (type.getSortWeight() == null) {
136
			List<PersonAttributeType> allTypes = Context.getPersonService().getAllPersonAttributeTypes();
137
			if (allTypes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
138
				type.setSortWeight(allTypes.get(allTypes.size() - 1).getSortWeight() + 1);
139
			} else {
246
		List<RelationshipType> types = dao.getRelationshipTypes(relationshipTypeName, null);
247
		
248
		if (types.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
249
			return null;
250
		} else {
514
	 */
515
	@Transactional(readOnly = true)
516
	public List<PersonAttributeType> getPersonAttributeTypes(PERSON_TYPE personType, ATTR_VIEW_TYPE viewType)
The Cyclomatic Complexity of this method "getPersonAttributeTypes" is 25 which is greater than 10 authorized.     NEW  
Methods should not be too complex
517
	        throws APIException {
518
		AdministrationService as = Context.getAdministrationService();
520
		String attrString = "";
521
		
522
		// TODO cache the global properties to speed this up??
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
523
		// Is hibernate taking care of caching and not hitting the db every time? (hopefully it is)
524
		if (viewType == null) {
546
				attrString = userViewing;
547
			} else {
548
				log.fatal("Should not be here");
Define a constant instead of duplicating this literal "Should not be here" 3 times.     NEW  
String literals should not be duplicated
549
			}
550
		} else if (viewType == ATTR_VIEW_TYPE.HEADER) {
566
		
567
		// the java list object to hold the values from the global properties
568
		List<String> attrNames = new Vector<String>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
569
		
570
		// split the comma delimited string into a java list object
573
				if (s != null) {
574
					s = s.trim();
575
					if (s.length() > 0) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
576
						attrNames.add(s);
577
					}
581
		
582
		// the actual list we'll be returning
583
		List<PersonAttributeType> attrObjects = new Vector<PersonAttributeType>();
Replace the synchronized class "Vector" by an unsynchronized one such as "ArrayList" or "LinkedList".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
584
		
585
		// get the PersonAttribute objects for each name/id
586
		if (attrNames.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
587
			for (String nameOrId : attrNames) {
588
				if (nameOrId.matches("\\d")) {
933
		String locked = Context.getAdministrationService().getGlobalProperty(
934
		    OpenmrsConstants.GLOBAL_PROPERTY_PERSON_ATRIBUTE_TYPES_LOCKED, "false");
935
		if (locked.toLowerCase().equals("true")) {
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.     NEW  
Case insensitive string comparisons should be made without intermediate upper or lower casing
936
			throw new PersonAttributeTypeLockedException();
937
		}
1
New issues
272
	@Transactional(readOnly = true)
273
	public List<PatientProgram> getPatientPrograms(Cohort cohort, Collection<Program> programs) {
274
		if (cohort.getMemberIds().size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
275
			return dao.getPatientPrograms(null, programs);
276
		} else {
3
New issues
210
			return;
211
		}
212
		if (Context.getEncounterService().getEncountersByVisit(visit, true).size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
213
			throw new APIException("Visit.purge.inUse", (Object[]) null);
214
		}
367
			}
368
			
369
			if (visitTypesToStop.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
370
				int counter = 0;
371
				Date stopDate = new Date();
374
					nextVisit.setStopDatetime(stopDate);
375
					dao.saveVisit(nextVisit);
376
					if (counter++ > 50) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
377
						//ensure changes are persisted to DB before reclaiming memory
378
						Context.flushSession();
1
New issues
73
		 * Use this code snippet instead if we think that fetching the clob is fast enough
74
		 * 
75
		ClobDatatypeStorage storage = Context.getDatatypeService().getClobDatatypeStorageByUuid(referenceString);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
76
		if (storage == null)
77
			return Context.getMessageSourceService().getMessage("CustomDatatype.error.missingValue");
3
New issues
79
		}
80
		
81
		StringBuffer dateString = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
82
		dateString.append(s.substring(0, 4)); // year
83
		if (s.length() >= 6) {
226
		s = s.replace(timeZoneOffset, ""); // remove the timezone from the string
227
		
228
		StringBuffer timeString = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
229
		
230
		if (s.length() < 2 || s.length() > 16) {
296
		}
297
		
298
		//TODO Should take care of the case where the user is using removable media, this might explode
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
299
		return OpenmrsUtil.getDirectoryInApplicationDataDirectory(archiveDir);
300
	}
2
New issues
168
			
169
		} else {
170
			// TODO: Add a global property that enables different behavior here.
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
171
			log.info("Ignoring ADT_A28 message because patient (" + patientId + ") already exists.");
172
		}
256
			}
257
		}
258
		if (goodIdentifiers.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
259
			throw new HL7Exception("PID segment has no recognizable patient identifiers.");
260
		}
6
New issues
184
		// TODO: ideally, we would branch or alter our behavior based on the
185
		// sending application.
186
		// String sendingApplication = getSendingApplication(oru);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
187
		
188
		// validate message
204
		}
205
		
206
		HL7Service hl7Service = Context.getHL7Service();
Remove this unused "hl7Service" local variable.     NEW  
Unused local variables should be removed
Dead store to hl7Service in org.openmrs.hl7.handler.ORUR01Handler.processORU_R01(ORU_R01)     NEW  
Dodgy - Dead store to local variable
207
		
208
		// create the encounter
674
				obs.setConcept(concept);
675
				if (concept.getDatatype().isBoolean()) {
676
					obs.setValueBoolean(value.equals("1"));
Move the "1" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
677
				} else if (concept.getDatatype().isNumeric()) {
678
					try {
689
					boolean isValidAnswer = false;
690
					Collection<ConceptAnswer> conceptAnswers = concept.getAnswers();
691
					if (conceptAnswers != null && conceptAnswers.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
692
						for (ConceptAnswer conceptAnswer : conceptAnswers) {
693
							if (conceptAnswer.getAnswerConcept().getId().equals(answer.getId())) {
1197
		Calendar cal = Calendar.getInstance();
1198
		cal.set(year, month, day, hour, min, sec);
1199
		// if (cal.getTimeZone().getRawOffset() != timeZoneOffsetMillis) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
1200
		// TimeZone tz = (TimeZone)TimeZone.getDefault().clone();
1201
		// tz.setRawOffset(timeZoneOffsetMillis);
11
New issues
402
	@Transactional(readOnly = true)
403
	public Integer resolveUserId(XCN xcn) throws HL7Exception {
404
		// TODO: properly handle family and given names. For now I'm treating
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
405
		// givenName+familyName as a username.
406
		String idNumber = xcn.getIDNumber().getValue();
410
		// unused
411
		// String assigningAuthority = xcn.getAssigningAuthority()
412
		// .getUniversalID().getValue();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
413
		
414
		/*
415
		 * if ("null".equals(familyName)) familyName = null; if
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
416
		 * ("null".equals(givenName)) givenName = null; if
417
		 * ("null".equals(assigningAuthority)) assigningAuthority = null;
418
		 */
419
		if (idNumber != null && idNumber.length() > 0) {
420
			// log.debug("searching for user by id " + idNumber);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
421
			try {
422
				Integer userId = Integer.valueOf(idNumber);
429
			}
430
		} else {
431
			// log.debug("searching for user by name");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
432
			try {
433
				StringBuilder username = new StringBuilder();
441
					username.append(givenName);
442
				}
443
				// log.debug("looking for username '" + username + "'");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
444
				User user = Context.getUserService().getUserByUsername(username.toString());
445
				return user.getUserId();
475
			if (persons.size() == 1) {
476
				return persons.get(0).getPersonId();
477
			} else if (persons.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
478
				log.error("Couldn't find a person named " + givenName + " " + familyName);
479
				return null;
561
		// TODO other potential identifying characteristics in PID we could use
562
		// to identify the patient
563
		// XPN[] patientName = pid.getPersonName();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
564
		// String gender = pid.getAdministrativeSex().getValue();
565
		// TS dateOfBirth = pid.getDateTimeOfBirth();
618
					List<PatientIdentifier> matchingIds = Context.getPatientService().getPatientIdentifiers(hl7PersonId,
619
					    Collections.singletonList(pit), null, null, null);
620
					if (matchingIds == null || matchingIds.size() < 1) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
621
						// no matches
622
						log.warn("NO matches found for " + hl7PersonId);
711
			            OpenmrsConstants.GLOBAL_PROPERTY_IGNORE_MISSING_NONLOCAL_PATIENTS, "false"));
712
			if (e.getCause() != null
713
			        && e.getCause().getMessage().equals("Could not resolve patient")
Move the "Could not resolve patient" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
714
			        && !"local".equals(hl7InQueue.getHL7Source().getName())
715
			        && "true".equals(Context.getAdministrationService().getGlobalProperty(
1023
		// while we still we have any archives to be processed, process them
1024
		while (Hl7InArchivesMigrateThread.isActive() && Hl7InArchivesMigrateThread.getTransferStatus() == Status.RUNNING
1025
		        && hl7InArchives != null && hl7InArchives.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
1026
			
1027
			Iterator<HL7InArchive> iterator = hl7InArchives.iterator();
7
New issues
45
	protected List<String> requiredElements;
46
	
47
	protected int maxTokens = 0; // The largest number of tokens on one given line
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
48
	
49
	protected String startDate;
101
					currToken.put("displaySize", this.getSizeMappings().get(realToken));
102
					currToken.put("codeName", realToken);
103
					//numTokens++;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
104
					ret.add(currToken);
105
				}
120
					currToken.put("displaySize", this.getSizeMappings().get(realToken));
121
					currToken.put("codeName", realToken);
122
					//numTokens++;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
123
					ret.add(currNonToken);
124
					ret.add(currToken);
140
						currToken.put("displaySize", this.getSizeMappings().get(realToken));
141
						currToken.put("codeName", realToken);
142
						//numTokens++;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
143
						ret.add(currToken);
144
					}
163
			currToken.put("displaySize", this.getSizeMappings().get(realToken));
164
			currToken.put("codeName", realToken);
165
			//numTokens++;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
166
			
167
			ret.add(currToken);
324
	public int getMaxTokens() {
325
		if (maxTokens == -1) {
326
			getLines(); // initialize the maxTokens variable
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
327
		}
328
		
369
	public List<String> nonUniqueStringsGoLast(List<String> strListArg) {
370
		List<String> dup = new ArrayList<String>();
371
		List<String> strList = new ArrayList(strListArg); // copy the list so we don't get concurrentmodification exceptions
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
372
		for (String s : strList) {
373
			for (String sInner : strList) {
1
New issues
52
	
53
	public String toString() {
54
		StringBuffer result = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
55
		
56
		if (transformOperator != null) {
7
New issues
31
 * get to the full-featured objects instead of the simplified values in the date-value pairs.<br>
32
 * <br>
33
 * TODO: eliminate unnecessary methods (toDatetime(), getDatetime(), and getDate() should all do the
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
34
 * same thing)<br>
35
 * TODO: better support/handling of NULL_RESULT
112
	 */
113
	public Result(List<Result> list) {
114
		if (!(list == null || list.size() < 1)) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
115
			this.addAll(list);
116
		}
637
			}
638
		}
639
		StringBuffer s = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
640
		for (Result r : this) {
641
			if (s.length() > 0) {
761
	}
762
	
763
	//TODO rewrite this method
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
764
	//
765
	//	/**
766
	//	 * @see java.lang.Object#hashCode()
767
	//	 */
768
	//	public int hashCode() {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
769
	//		int hashCode = 49867; // some random number
770
	//		hashCode += this.hashCode();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
771
	//	
772
	//		return hashCode;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
773
	//	}
774
	
1
New issues
15
import org.springframework.context.HierarchicalMessageSource;
16
import org.springframework.context.MessageSource;
17
import org.springframework.transaction.annotation.Transactional;
Remove this unused import 'org.springframework.transaction.annotation.Transactional'.     NEW  
Useless imports should be removed
18

                  
19
/**
1
New issues
102
	 */
103
	public void putAll(Map<? extends String, ? extends PresentationMessage> t) {
104
		//Map<String, PresentationMessage> compatibleMap = new HashMap<String, PresentationMessage>();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
105
		for (Entry<? extends String, ? extends PresentationMessage> entry : t.entrySet()) {
106
			put(entry.getKey(), entry.getValue());
1
New issues
58
		
59
		for (Locale locale : localizedMap.keySet()) {
60
			PresentationMessageMap codeMessageMap = localizedMap.get(locale);
org.openmrs.messagesource.impl.CachedMessageSource.getPresentations() makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
61
			allMessages.addAll(codeMessageMap.values());
62
		}
2
New issues
94
		}
95
		
96
		if (foundLocales.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
97
			log.warn("no locales found.");
98
		}
144
				}
145
			}
146
			catch (Exception e) {
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
147
				// skip over errors in loading a single file
148
				log.error("Unable to load properties from file: " + propertiesFile.getFilename());
4
New issues
292
		PatientService ps = Context.getPatientService();
293
		List<PatientProgram> patientPrograms = new ArrayList<PatientProgram>();
294
		//List<PatientState> patientStates = new ArrayList<PatientState>();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
295
		Map<String, PatientProgram> knownPatientPrograms = new HashMap<String, PatientProgram>();
296
		Map<String, Program> programsByName = new HashMap<String, Program>();
331
				String[] temp = s.split(",");
332
				/* We're using a cache of 'knownPatientPrograms' instead of the following commented code
333
				PatientIdentifierType pit = ps.getPatientIdentifierType(temp[0]);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
334
				String identifier = temp[1];
335
				List<PatientIdentifier> pis = ps.getPatientIdentifiers(identifier, pit);
342
					throw new RuntimeException("Couldn't find program \"" + temp[2] + "\" in " + programsByName);
343
				}
344
				//ProgramWorkflow wf = pws.getWorkflow(program, temp[3]);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
345
				ProgramWorkflow wf = program.getWorkflowByName(temp[3]);
346
				if (wf == null) {
348
					        + program.getAllWorkflows() + ")");
349
				}
350
				//ProgramWorkflowState st = pws.getState(wf, temp[4]);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
351
				ProgramWorkflowState st = wf.getStateByName(temp[4]);
352
				if (st == null) {
1
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
2
New issues
547
				}
548
				catch (ClassNotFoundException e) {
549
					log.warn("Unable to load class for extension: " + point, e);
Define a constant instead of duplicating this literal "Unable to load class for extension: " 3 times.     NEW  
String literals should not be duplicated
550
				}
551
				catch (IllegalAccessException e) {
715
		}
716
		
717
		StringBuffer sb = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
718
		
719
		// if exceptionMessage is not null, append it
8
New issues
76
	 * This is also used to fix: https://tickets.openmrs.org/browse/TRUNK-4053
77
	 */
78
	private Map<String, Class<?>> loadedClasses = new HashMap<String, Class<?>>();
Remove this unused "loadedClasses" private field.     NEW  
Unused private fields should be removed
79
	
80
	/**
507
		
508
		if (log.isDebugEnabled()) {
509
			StringBuffer buf = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
510
			buf.append("New code URL's populated for module " + getModule() + ":\r\n");
511
			for (URL u : newUrls) {
742
		String libname = System.mapLibraryName(name);
743
		String result = null;
744
		//TODO
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
745
		//PathResolver pathResolver = ModuleFactory.getPathResolver();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
746
		//		for (Library lib : getModule().getLibraries()) {
747
		//			if (lib.isCodeLibrary()) {
756
		//				if (log.isDebugEnabled()) {
757
		//					log.debug("findLibrary(String): URL " + libUrl
758
		//							+ " resolved as local file " + libFile);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
759
		//				}
760
		//				if (libFile.isFile()) {
766
		//			// we have some kind of non-local URL
767
		//			// try to copy it to local temporary file
768
		//			libFile = (File) libraryCache.get(libUrl);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
769
		//			if (libFile != null) {
770
		//				if (libFile.isFile()) {
776
		//			if (libraryCache.containsKey(libUrl)) {
777
		//				// already tried to cache this library
778
		//				break;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
779
		//			}
780
		//			libFile = cacheLibrary(libUrl, libname);
1004
			}
1005
		}
1006
		//		if (resourceLoader != null) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
1007
		//			for (Enumeration enm = resourceLoader.findResources(name);
1008
		//					enm.hasMoreElements();) {
10
New issues
195
		Map<String, Module> loadedModulesMap = getLoadedModulesMapPackage();
196
		for (String key : loadedModules.keySet()) {
197
			Module m = loadedModules.get(key);
org.openmrs.module.ModuleFactory.loadModules(List) makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
198
			Map<String, String> startBeforeModules = m.getStartBeforeModulesMap();
199
			if (startBeforeModules.size() > 0) {
217
		
218
		// loop over and try starting each of the loaded modules
219
		if (getLoadedModules().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
220
			
221
			List<Module> modules = getModulesThatShouldStart();
282
			// if a 'moduleid.started' property doesn't exist, start the module anyway
283
			// as this is probably the first time they are loading it
284
			if (startedProp == null || startedProp.equals("true") || "true".equalsIgnoreCase(mandatoryProp)
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
285
			        || mod.isMandatory() || isCoreToOpenmrs) {
286
				modules.add(mod);
470
		Map<String, Module> map = new WeakHashMap<String, Module>();
471
		for (String key : loadedModules.keySet()) {
472
			map.put(loadedModules.get(key).getPackageName(), loadedModules.get(key));
org.openmrs.module.ModuleFactory.getLoadedModulesMapPackage() makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
473
		}
474
		return map;
658
				// into spring yet.  All advice for all modules must be reloaded
659
				// a spring context refresh anyway, so skip the advice loading here
660
				// loadAdvice(module);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
661
				
662
				// map extension point to a list of extensions for this module only
756
				// (Unfortunately, placing the call here will duplicate work
757
				// done at initial app startup)
758
				if (module.getPrivileges().size() > 0 || module.getGlobalProperties().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
759
					log.debug("Updating core dataset");
760
					Context.checkCoreDataset();
896
			catch (ClassNotFoundException e) {
897
				log.warn("Could not load advice point: " + advice.getPoint(), e);
898
				//throw new ModuleException("Could not load advice point: " + advice.getPoint(), e);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
899
			}
900
		}
1115
			for (Module dependentModule : startedModulesCopy) {
1116
				if (dependentModule != null && !dependentModule.equals(mod)) {
1117
					if (dependentModule.getRequiredModules() != null && dependentModule.getRequiredModules().contains(modulePackage)) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
1118
						dependentModulesStopped.add(dependentModule);
1119
						dependentModulesStopped.addAll(stopModule(dependentModule, skipOverStartedProperty, isFailedStartup));
1169
						try {
1170
							List<Extension> tmpExtensions = getExtensions(extId);
1171
							if (tmpExtensions == null) {
Redundant nullcheck of tmpExtensions, which is known to be non-null in org.openmrs.module.ModuleFactory.stopModule(Module, boolean, boolean)     NEW  
Dodgy - Redundant nullcheck of value known to be non-null
1172
								tmpExtensions = new Vector<Extension>();
1173
							}
4
New issues
131
		if (log.isDebugEnabled()) {
132
			Collection<Module> modules = ModuleFactory.getStartedModules();
133
			if (modules == null || modules.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
134
				log.debug("No modules loaded");
135
			} else {
920
		
921
		// any module ids left in the list are not started
922
		if (mandatoryModuleIds.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
923
			throw new MandatoryModuleException(mandatoryModuleIds);
924
		}
1106
				
1107
				if (packagesProvided.add(packageName)) {
1108
					if (log.isTraceEnabled()) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
1109
						log.trace("Adding module's jarentry with package: " + packageName);
1110
					}
1
New issues
13 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
1
New issues
10
package org.openmrs.notification;
11

                  
12
import java.util.Collection;
Remove this unused import 'java.util.Collection'.     NEW  
Useless imports should be removed
13
import java.util.List;
14

                  
6
New issues
Class org.openmrs.notification.Note defines non-transient non-serializable instance field noteType     NEW
Non-transient non-serializable instance field in serializable class
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
48
	private NoteType noteType;
49
	
50
	//private Observation observation;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
51
	//private Encounter encounter;
52
	//private User createdBy;		
71
	
72
	public Date getDateChanged() {
73
		return dateChanged;
org.openmrs.notification.Note.getDateChanged() may expose internal representation by returning Note.dateChanged     NEW  
Malicious code vulnerability - May expose internal representation by returning reference to mutable object
74
	}
75
	
76
	public void setDateChanged(Date dateChanged) {
77
		this.dateChanged = dateChanged;
org.openmrs.notification.Note.setDateChanged(Date) may expose internal representation by storing an externally mutable object into Note.dateChanged     NEW  
Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object
78
	}
79
	
80
	public Date getDateCreated() {
81
		return dateCreated;
org.openmrs.notification.Note.getDateCreated() may expose internal representation by returning Note.dateCreated     NEW  
Malicious code vulnerability - May expose internal representation by returning reference to mutable object
82
	}
83
	
84
	public void setDateCreated(Date dateCreated) {
85
		this.dateCreated = dateCreated;
org.openmrs.notification.Note.setDateCreated(Date) may expose internal representation by storing an externally mutable object into Note.dateCreated     NEW  
Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object
86
	}
87
	
5
New issues
31
	 */
32
	@Authorized(PrivilegeConstants.GET_NOTE)
33
	public List<Note> getNotes(User user) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
34
	
35
	/**
38
	 * @param note the Note being created
39
	 */
40
	public void createNote(Note note) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
41
	
42
	/**
45
	 * @param noteId the internal primary key identifier for a Note
46
	 */
47
	public Note getNote(Integer noteId) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
48
	
49
	/**
52
	 * @param note note being updated
53
	 */
54
	public void updateNote(Note note) throws Exception;
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
55
	
56
	/**
63
	 */
64
	@Authorized(PrivilegeConstants.DELETE_NOTE)
65
	public Note voidNote(Note note, String reason) throws APIException;
Remove the declaration of thrown exception 'org.openmrs.api.APIException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
66
}
1
New issues
101
			// getting here means we passed in no user or a blank user.
102
			// a null recipient column means get stuff for the anonymous user
103
			//crit.add(Expression.isNull("recipient.recipient"));
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
104
			
105
			// returning an empty list for now because the above throws an error.
2
New issues
164
		User user = Context.getUserService().getUser(recipientId);
165
		message.addRecipient(user.getUserProperty(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS));
166
		// message.setFormat( user( OpenmrsConstants.USER_PROPERTY_NOTIFICATION_FORMAT ) );
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
167
		Context.getMessageService().sendMessage(message);
168
	}
180
			message.addRecipient(address);
181
		}
182
		// message.setFormat( user.getProperty( OpenmrsConstants.USER_PROPERTY_NOTIFICATION_FORMAT ) );
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
183
		Context.getMessageService().sendMessage(message);
184
	}
7
New issues
Class org.openmrs.notification.impl.NoteServiceImpl defines non-transient non-serializable instance field log     NEW
Non-transient non-serializable instance field in serializable class
Class org.openmrs.notification.impl.NoteServiceImpl defines non-transient non-serializable instance field dao     NEW
Non-transient non-serializable instance field in serializable class
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
42
	 * Logger
43
	 */
44
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
45
	
46
	/**
56
	 * @throws Exception
57
	 */
58
	public Collection<Note> getNotes() throws Exception {
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
59
		log.info("Get all notes");
60
		return getNoteDAO().getNotes();
102
	 */
103
	public List<Note> getNotes(User user) throws Exception {
104
		// TODO Auto-generated method stub
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
105
		return null;
Return an empty collection instead of null.     NEW  
Empty arrays and collections should be returned instead of null
106
	}
107
	
113
	 * @throws APIException
114
	 */
115
	public Note voidNote(Note note, String reason) throws APIException {
Remove the declaration of thrown exception 'org.openmrs.api.APIException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
116
		log.debug("voiding note because " + reason);
117
		return dao.voidNote(note, reason);
1
New issues
96
		MimeMessage mimeMessage = new MimeMessage(session);
97
		
98
		// TODO Need to test the null case.  
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
99
		// Transport should use default mail.from value defined in properties.
100
		if (message.getSender() != null) {
2
New issues
77
			title = title.replace("." + extension, "");
78
			outputfile = new File(dir, title + "." + extension);
79
			// outputfile = new File(dir, title);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
80
		}
81
		
149
		} else if (file.delete()) {
150
			obs.setComplexData(null);
151
			// obs.setValueComplex(null);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
152
			return true;
153
		}
1
New issues
290
	}
291
	
292
	//public void setPriorDateOfDeathEstimated(boolean priorDateOfDeathEstimated) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
293
	public void setPriorDateOfDeathEstimated(Boolean priorDateOfDeathEstimated) {
294
		this.priorDateOfDeathEstimated = priorDateOfDeathEstimated;
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
28
public class CohortEditor extends PropertyEditorSupport {
29
	
30
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
31
	
32
	public CohortEditor() {
37
	 * @should set using uuid
38
	 */
39
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
40
		if (StringUtils.hasText(text)) {
41
			try {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptAnswerEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptAnswerEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		ConceptService cs = Context.getConceptService();
42
		if (StringUtils.hasText(text)) {
1
New issues
63
			for (String id : conceptIds) {
64
				id = id.trim();
65
				if (!id.equals("") && !requestConceptIds.contains(id)) { //remove whitespace, blank lines, and duplicates
Move the "" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
66
					requestConceptIds.add(id);
67
				}
2
New issues
6 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
33
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
34
	 */
35
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
36
		ConceptService conceptService = Context.getConceptService();
37
		if (Context.isAuthenticated() && StringUtils.hasText(text)) {
4
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptClassEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptClassEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		log.debug("Setting text: " + text);
42
		ConceptService cs = Context.getConceptService();
45
				setValue(cs.getConceptClass(Integer.valueOf(text)));
46
			}
47
			catch (Exception ex) {
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
48
				ConceptClass conceptClass = cs.getConceptClassByUuid(text);
49
				setValue(conceptClass);
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptDatatypeEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptDatatypeEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		log.debug("setting text: " + text);
42
		ConceptService cs = Context.getConceptService();
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		ConceptService cs = Context.getConceptService();
42
		if (StringUtils.hasText(text)) {
1
New issues
4 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptNameEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptNameEditor() {
40
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
41
	 */
42
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
43
		ConceptService cs = Context.getConceptService();
44
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptNumericEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptNumericEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		ConceptService cs = Context.getConceptService();
42
		if (StringUtils.hasText(text)) {
1
New issues
4 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
1
New issues
59
			for (String id : conceptIds) {
60
				id = id.trim();
61
				if (!id.equals("") && !requestConceptIds.contains(Integer.valueOf(id))) { //remove whitespace, blank lines, and duplicate entries
Move the "" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
62
					requestConceptIds.add(Integer.valueOf(id));
63
				}
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ConceptSourceEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ConceptSourceEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		log.debug("Setting text: " + text);
42
		ConceptService cs = Context.getConceptService();
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class DrugEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public DrugEditor() {
44
	 * @should fail if drug does not exist with non-empty identifier
45
	 */
46
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
47
		ConceptService es = Context.getConceptService();
48
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class EncounterEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public EncounterEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		EncounterService es = Context.getEncounterService();
42
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class EncounterTypeEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public EncounterTypeEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		EncounterService ps = Context.getEncounterService();
42
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class FormEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public FormEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		FormService ps = Context.getFormService();
42
		if (StringUtils.hasText(text)) {
2
New issues
6 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
38
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		LocationService ls = Context.getLocationService();
42
		if (Context.isAuthenticated() && StringUtils.hasText(text)) {
5
New issues
5 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class LocationEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public LocationEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		LocationService ls = Context.getLocationService();
42
		if (StringUtils.hasText(text)) {
60
		Location t = (Location) getValue();
61
		if (t == null && Context.isAuthenticated()) {
62
			return null; //return Context.getAuthenticatedUser().getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION);
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
63
		} else {
64
			if (t != null) {
3
New issues
3 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
27
public class LocationTagEditor extends PropertyEditorSupport {
28
	
29
	private static Log log = LogFactory.getLog(LocationTagEditor.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
30
	
31
	public LocationTagEditor() {
38
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		LocationService ls = Context.getLocationService();
42
		if (Context.isAuthenticated() && StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class OrderEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	/**
37
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
38
	 */
39
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
40
		OrderService ps = Context.getOrderService();
41
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class PatientEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	/**
37
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
38
	 */
39
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
40
		PatientService ps = Context.getPatientService();
41
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class PatientIdentifierTypeEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public PatientIdentifierTypeEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		PatientService ps = Context.getPatientService();
42
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class PersonAttributeEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	/**
35
	 * @should set using uuid
36
	 */
37
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
38
		PersonService ps = Context.getPersonService();
39
		if (StringUtils.hasText(text)) {
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class PersonAttributeTypeEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	/**
35
	 * @should set using uuid
36
	 */
37
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
38
		PersonService ps = Context.getPersonService();
39
		if (StringUtils.hasText(text)) {
1
New issues
4 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
New issues
3 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ProgramWorkflowEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ProgramWorkflowEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		ProgramWorkflowService pws = Context.getProgramWorkflowService();
42
		if (StringUtils.hasText(text)) {
3
New issues
3 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class ProgramWorkflowStateEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public ProgramWorkflowStateEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		ProgramWorkflowService pws = Context.getProgramWorkflowService();
42
		if (StringUtils.hasText(text)) {
1
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
29
public class UserEditor extends PropertyEditorSupport {
30
	
31
	private Log log = LogFactory.getLog(this.getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
32
	
33
	public UserEditor() {
38
	 * @should set using uuid
39
	 */
40
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
41
		UserService ps = Context.getUserService();
42
		if (StringUtils.hasText(text)) {
5
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
27
public class VisitEditor extends PropertyEditorSupport {
28
	
29
	private static final Log log = LogFactory.getLog(VisitEditor.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Remove this unused "log" private field.     NEW  
Unused private fields should be removed
30
	
31
	public VisitEditor() {
36
	 * @should set using uuid
37
	 */
38
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
39
		VisitService vs = Context.getVisitService();
40
		if (StringUtils.hasText(text)) {
42
				setValue(vs.getVisit(Integer.valueOf(text)));
43
			}
44
			catch (Exception ex) {
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
45
				Visit v = vs.getVisitByUuid(text);
46
				setValue(v);
5
New issues
2 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.     NEW
Branches should have sufficient coverage by unit tests
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
27
public class VisitTypeEditor extends PropertyEditorSupport {
28
	
29
	private static final Log log = LogFactory.getLog(VisitTypeEditor.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Remove this unused "log" private field.     NEW  
Unused private fields should be removed
30
	
31
	public VisitTypeEditor() {
36
	 * @should set using uuid
37
	 */
38
	public void setAsText(String text) throws IllegalArgumentException {
Remove the declaration of thrown exception 'java.lang.IllegalArgumentException' which is a runtime exception.     NEW  
Throws declarations should not be redundant
39
		VisitService vs = Context.getVisitService();
40
		if (StringUtils.hasText(text)) {
42
				setValue(vs.getVisitType(Integer.valueOf(text)));
43
			}
44
			catch (Exception ex) {
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
45
				VisitType v = vs.getVisitTypeByUuid(text);
46
				setValue(v);
1
New issues
114
	public String getAsText() {
115
		Collection<ProgramWorkflow> pws = (Collection<ProgramWorkflow>) getValue();
116
		if (pws == null || pws.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
117
			return ":";
118
		} else {
4
New issues
77
	public static final int DAYS_PER_WEEK = 7;
78
	
79
	//public static DEFAULT_DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
80
	public static final int DAILY = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
81
	
82
	public static final int WEEKLY = DAILY * DAYS_PER_WEEK;
83
	
84
	//public static final int MONTHLY; 
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
85
	//public static final int ANNUALLY;
86
	
201
	 * @param startTime start time for the task
202
	 */
203
	/*	public void setStartTime(String startTime) { 
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
204
			try {
205
		            this.startTime = this.dateFormatter.parse(startTime);
207
			catch (Exception e) { 
208
				//If there's an error, we'll just set the start time to now.
209
				// TODO: This might not be the desired behavior, so I'll have to come back to it.
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
210
		             this.startTime = new	             Date(); 
211
		             }
2
New issues
10
package org.openmrs.scheduler;
11

                  
12
import java.io.PrintWriter;
Remove this unused import 'java.io.PrintWriter'.     NEW  
Useless imports should be removed
13
import java.io.StringWriter;
Remove this unused import 'java.io.StringWriter'.     NEW  
Useless imports should be removed
14
import java.util.Calendar;
15
import java.util.Date;
1
New issues
17
import org.apache.commons.logging.LogFactory;
18
import org.openmrs.BaseOpenmrsMetadata;
19
import org.openmrs.User;
Remove this unused import 'org.openmrs.User'.     NEW  
Useless imports should be removed
20

                  
21
/**
4
New issues
78
	 * @throws DAOException
79
	 */
80
	//public void createSchedule(Schedule schedule) throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
81
	/**
82
	 * Get schedule by internal identifier
103
	 * @throws DAOException
104
	 */
105
	//public void updateSchedule(Schedule schedule) throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
106
	/**
107
	 * Get all schedules.
110
	 * @throws DAOException
111
	 */
112
	//public Set<Schedule> getSchedules() throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
113
	/**
114
	 * Delete schedule from database.
117
	 * @throws DAOException
118
	 */
119
	//public void deleteSchedule(Schedule schedule) throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
120
}
4
New issues
148
	 * @throws DAOException
149
	 */
150
	//public void createSchedule(Schedule schedule) throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
151
	/**
152
	 * Get schedule by internal identifier
172
	 * @throws DAOException
173
	 */
174
	//public void updateSchedule(Schedule schedule) throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
175
	/**
176
	 * Get all schedules.
179
	 * @throws DAOException
180
	 */
181
	//public Set<Schedule> getAllSchedules() throws DAOException;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
182
	/**
183
	 * Delete schedule from database.
186
	 * @throws DAOException
187
	 */
188
	//public void deleteSchedule(Schedule schedule) throws DAOException;	
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
189
}
1
New issues
207
			TimerSchedulerTask schedulerTask = scheduledTasks.get(taskDefinition.getId());
208
			if (schedulerTask != null) {
209
				//schedulerTask.cancel();					
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
210
				log.info("Shutting down the existing instance of this task to avoid conflicts!!");
211
				schedulerTask.shutdown();
1
New issues
100
				
101
				// returning null causes the field to be blanked out
102
				//return null;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
103
			}
104
		}
6
New issues
245
	 * @should always have a valid update to latest file
246
	 */
247
	public static boolean updatesRequired() throws Exception {
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
248
		log.debug("checking for updates");
249
		List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges();
253
		// returning true here stops the openmrs startup and shows
254
		// the user the maintenance wizard for updates
255
		if (isLocked() && changesets.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
256
			// if there is a db lock but there are no db changes we undo the
257
			// lock
261
		}
262
		
263
		return changesets.size() > 0;
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
264
	}
265
	
275
		
276
		List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(changeLogFilenames);
277
		return changesets.size() > 0;
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
278
	}
279
	
580
	 */
581
	@Authorized(PrivilegeConstants.GET_DATABASE_CHANGES)
582
	public static List<OpenMRSChangeSet> getUnrunDatabaseChanges() throws Exception {
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
583
		return getUnrunDatabaseChanges(CHANGE_LOG_FILE);
584
	}
594
	 */
595
	@Authorized(PrivilegeConstants.GET_DATABASE_CHANGES)
596
	public static List<OpenMRSChangeSet> getUnrunDatabaseChanges(String... changeLogFilenames) throws Exception {
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
597
		log.debug("Getting unrun changesets");
598
		
1
New issues
146
	 */
147
	public String toString() {
148
		StringBuffer ret = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
149
		if (low != null && low.doubleValue() != Double.NEGATIVE_INFINITY) {
150
			ret.append(">");
1
New issues
222
	public static String conceptToString(Concept concept, ConceptName localizedName) {
223
		return concept.getConceptId() + "^" + localizedName.getName() + "^" + HL7Constants.HL7_LOCAL_CONCEPT; // + "^"
224
		// + localizedName.getConceptNameId() + "^" + localizedName.getName() + "^" + FormConstants.HL7_LOCAL_CONCEPT_NAME;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
225
	}
226
	
2
New issues
10
package org.openmrs.util;
11

                  
12
import java.io.PrintWriter;
Remove this unused import 'java.io.PrintWriter'.     NEW  
Useless imports should be removed
13
import java.io.StringWriter;
Remove this unused import 'java.io.StringWriter'.     NEW  
Useless imports should be removed
14
import java.text.DateFormat;
15
import java.text.NumberFormat;
1
New issues
79
			String line;
80
			while ((line = rd.readLine()) != null) {
81
				response = String.format("%s%s\n", response, line);
Format string should use %n rather than \n in org.openmrs.util.HttpClient.post(Map)     NEW  
Format string should use %n rather than \n
82
			}
83
			
1
New issues
16
import org.apache.commons.logging.LogFactory;
17

                  
18
import sun.net.www.http.KeepAliveCache;
Replace this usage of Sun classes by ones from the Java API.     NEW  
Classes from "sun.*" packages should not be used
19

                  
20
/**
4
New issues
11

                  
12
import java.io.File;
13
import java.io.FilenameFilter;
Remove this unused import 'java.io.FilenameFilter'.     NEW  
Useless imports should be removed
14
import java.io.IOException;
15
import java.io.InputStream;
361
		log.info("this classloader hashcode: " + OpenmrsClassLoaderHolder.INSTANCE.hashCode());
362
		
363
		//		List<Thread> threads = listThreads(rootGroup, "");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
364
		//		for (Thread thread : threads) {
365
		//			if (thread.getContextClassLoader() != null) {
366
		//				log.debug("context classloader on thread: " + thread.getName() + " is: "
367
		//				        + thread.getContextClassLoader().getClass().getName() + ":"
368
		//				        + thread.getContextClassLoader().hashCode());
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
369
		//				if (thread.getContextClassLoader() == OpenmrsClassLoaderHolder.INSTANCE) {
370
		//					thread.setContextClassLoader(OpenmrsClassLoaderHolder.INSTANCE.getParent());
371
		//					log.error("Cleared context classloader to save the world from memory leaks. thread: " + thread.getName()
372
		//					        + " ");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
373
		//				}
374
		//			}
11
New issues
120
public class OpenmrsUtil {
121
	
122
	private static Log log = LogFactory.getLog(OpenmrsUtil.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
123
	
124
	private static Map<Locale, SimpleDateFormat> dateFormatCache = new HashMap<Locale, SimpleDateFormat>();
219
	 */
220
	public static String getFileAsString(File file) throws IOException {
221
		StringBuffer fileData = new StringBuffer(1000);
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
222
		BufferedReader reader = new BufferedReader(new FileReader(file));
223
		char[] buf = new char[1024];
272
	 * @throws IOException thrown if an error occurs during read/write
273
	 */
274
	public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException {
The Cyclomatic Complexity of this method "copyFile" is 11 which is greater than 10 authorized.     NEW  
Methods should not be too complex
275
		if (inputStream == null || outputStream == null) {
276
			if (outputStream != null) {
278
					outputStream.close();
279
				}
280
				catch (Exception e) { /* pass */
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
281
				}
282
			}
308
				outputStream.close();
309
			}
310
			catch (Exception e) { /* pass */
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
311
			}
312
		}
1053
		if (filepath == null) {
1054
			if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) {
1055
				filepath = System.getProperty("user.home") + File.separator + ".OpenMRS";
Define a constant instead of duplicating this literal "user.home" 3 times.     NEW  
String literals should not be duplicated
1056
				if (!canWrite(new File(filepath))) {
1057
					log.warn("Unable to write to users home dir, fallback to: "
Define a constant instead of duplicating this literal "Unable to write to users home dir, fallback to: " 3 times.     NEW  
String literals should not be duplicated
1058
					        + OpenmrsConstants.APPLICATION_DATA_DIRECTORY_FALLBACK_UNIX);
1059
					filepath = OpenmrsConstants.APPLICATION_DATA_DIRECTORY_FALLBACK_UNIX + File.separator + "OpenMRS";
Define a constant instead of duplicating this literal "OpenMRS" 4 times.     NEW  
String literals should not be duplicated
1060
				}
1061
			} else {
1062
				if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) {
1063
					filepath = System.getProperty("user.home") + File.separator + ".OpenMRS";
1064
					if (!canWrite(new File(filepath))) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
1065
						log.warn("Unable to write to users home dir, fallback to: "
1066
						        + OpenmrsConstants.APPLICATION_DATA_DIRECTORY_FALLBACK_UNIX);
1070
					filepath = System.getProperty("user.home") + File.separator + "Application Data" + File.separator
1071
					        + "OpenMRS";
1072
					if (!canWrite(new File(filepath))) {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.     NEW  
Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
1073
						log.warn("Unable to write to users home dir, fallback to: "
1074
						        + OpenmrsConstants.APPLICATION_DATA_DIRECTORY_FALLBACK_WIN);
1614
	public static String generateUid(Integer size) {
1615
		Random gen = new Random();
1616
		StringBuffer sb = new StringBuffer(size);
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
1617
		for (int i = 0; i < size; i++) {
1618
			int ch = gen.nextInt() * 62;
1
New issues
20
import java.util.List;
21

                  
22
import org.azeckoski.reflectutils.ClassData;
Remove this unused import 'org.azeckoski.reflectutils.ClassData'.     NEW  
Useless imports should be removed
23
import org.azeckoski.reflectutils.ClassDataCacher;
24
import org.azeckoski.reflectutils.ClassFields;
6
New issues
88
		catch (NoSuchAlgorithmException e) {
89
			// Yikes! Can't encode password...what to do?
90
			log.error("Can't encode password because the given algorithm: " + algorithm + "was not found! (fail)", e);
Define a constant instead of duplicating this literal "Can't encode password because the given algorithm: " 3 times.     NEW  
String literals should not be duplicated
Define a constant instead of duplicating this literal "was not found! (fail)" 3 times.     NEW  
String literals should not be duplicated
91
			throw new APIException("system.cannot.find.password.encryption.algorithm", null, e);
92
		}
129
	 */
130
	private static String hexString(byte[] block) {
131
		StringBuffer buf = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
132
		char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
133
		int len = block.length;
184
			return "";
185
		}
186
		StringBuffer s = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
187
		for (int i = 0; i < b.length; i++) {
188
			s.append(Integer.toHexString(b[i] & 0xFF));
319
		new SecureRandom().nextBytes(initVector);
320
		
321
		// TODO get the following (better) method working
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
322
		// Cipher cipher = Cipher.getInstance(CIPHER_CONFIGURATION);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
323
		// AlgorithmParameters params = cipher.getParameters();
324
		// byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
1
New issues
40
		String conceptId = null;
41
		try {
42
			FileInputStream fis = new FileInputStream(appDataDir + System.getProperty("file.separator")
org.openmrs.util.UpgradeUtil.getConceptIdForUnits(String) may fail to close stream     NEW  
Bad practice - Method may fail to close stream
43
			        + DatabaseUtil.ORDER_ENTRY_UPGRADE_SETTINGS_FILENAME);
44
			props.load(fis);
2
New issues
38
			    connection.getUnderlyingConnection());
39
			Set<String> unmappedDoseUnits = getUnMappedText(doseUnits, connection);
40
			if (unmappedDoseUnits.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
41
				throw new CustomPreconditionFailedException(
42
				        "Upgrade failed because of the following unmapped drug order dose units that were found: ["
50
			    connection.getUnderlyingConnection());
51
			Set<String> unmappedFrequencies = getUnMappedText(frequencies, connection);
52
			if (unmappedFrequencies.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
53
				throw new CustomPreconditionFailedException(
54
				        "Upgrade failed because of the following unmapped drug order frequencies that were found: ["
2
New issues
140
				
141
				//for each name in the locale
142
				for (ConceptName nameInLocale : localeConceptNamesMap.get(conceptNameLocale)) {
org.openmrs.util.databasechange.ConceptValidatorChangeSet.validateAndCleanUpConcepts(JdbcConnection) makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
143
					if (StringUtils.isBlank(nameInLocale.getName())) {
144
						updateWarnings.add("ConceptName with id " + nameInLocale.getConceptNameId() + " ("
256
					        + conceptId + "' in locale '" + conceptNameLocale.getDisplayName() + "'");
257
					
258
					/*ConceptName chosenName = null;
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
259
					List<ConceptName> voidedNames = new ArrayList<ConceptName>();
260
					for (ConceptName duplicate : entry.getValue()) {
1
New issues
182
					connection.setAutoCommit(initialAutoCommit);
183
				}
184
				// connection.close();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
185
			}
186
			catch (DatabaseException e) {
1
New issues
107
			connection.setAutoCommit(false);
108
			
109
			if (database.getTypeName().equals("mysql")) {
Move the "mysql" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
110
				String updateSql = "update %s set " + columnName + " = uuid() where " + columnName + " is null";
111
				for (String tablename : tableNamesArray) {
1
New issues
231
				comment = comment.substring(9).trim();
232
				
233
				if (comment.equals("SAME-AS FROM RXNORM")) {
Move the "SAME-AS FROM RXNORM" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
234
					comment = "SAME-AS";
235
				}
1
New issues
86
		for (List<Object> row : results) {
87
			Integer conceptId = Integer.valueOf(row.get(0).toString());
88
			boolean isInitial = row.get(1).toString().equals("1");
Move the "1" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
89
			int num = Integer.parseInt(row.get(2).toString());
90
			if (isInitial && num > 0) {
2
New issues
128
		
129
		// run the command line string
130
		StringBuffer output = new StringBuffer();
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
131
		Integer exitValue = -1; // default to a non-zero exit value in case of exceptions
132
		try {
191
	 * @return process exit value
192
	 */
193
	private Integer execCmd(File wd, String[] cmdWithArguments, StringBuffer out) throws Exception {
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
194
		log.debug("executing command: " + Arrays.toString(cmdWithArguments));
195
		
2
New issues
29
	
30
	// Log for this class
31
	private static final Log log = LogFactory.getLog(ConceptMapTypeValidator.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
Remove this unused "log" private field.     NEW  
Unused private fields should be removed
32
	
33
	/**
2
New issues
97
		Concept conceptToValidate = (Concept) obj;
98
		//no name to validate, but why is this the case?
99
		if (conceptToValidate.getNames().size() == 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
100
			errors.reject("Concept.name.atLeastOneRequired");
101
			return;
223
					
224
				}
225
				/*if (map.getConceptMapType() == null) {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
226
					errors.rejectValue("conceptMappings[" + index + "].conceptMapType", "Concept.map.typeRequired",
227
					    "The concept map type is required for a concept map");
1
New issues
133
	private void validateSamePatientInOrderAndEncounter(Order order, Errors errors) {
134
		if (order.getEncounter() != null && order.getPatient() != null) {
135
			if (!order.getEncounter().getPatient().equals(order.getPatient())) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
136
				errors.rejectValue("encounter", "Order.error.encounterPatientMismatch");
137
			}
1
New issues
97
		if (!errors.hasErrors()) {
98
			// Validate PatientIdentifers
99
			if (patient.getIdentifiers() != null) {
Merge this if statement with the enclosing one.     NEW  
Collapsible "if" statements should be merged
100
				for (PatientIdentifier identifier : patient.getIdentifiers()) {
101
					errors.pushNestedPath("identifiers[" + index + "]");
1
New issues
131
		if (StringUtils.isBlank(personName.getFamilyName())
132
		        || StringUtils.isBlank(personName.getFamilyName().replaceAll("\"", ""))) {
133
			errors.rejectValue(getFieldKey("familyName", arrayInd, testInd), "Patient.names.required.given.family");
Define a constant instead of duplicating this literal "familyName" 3 times.     NEW  
String literals should not be duplicated
134
		}
135
		// Make sure the entered name value is sensible 
1
New issues
56
	 */
57
	@Override
58
	public void validate(Object target, Errors errors) {
The Cyclomatic Complexity of this method "validate" is 11 which is greater than 10 authorized.     NEW  
Methods should not be too complex
59
		if (log.isDebugEnabled()) {
60
			log.debug(this.getClass().getName() + ".validate...");
1
New issues
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.validation.Errors;
28
import org.springframework.validation.ValidationUtils;
Remove this unused import 'org.springframework.validation.ValidationUtils'.     NEW  
Useless imports should be removed
29
import org.springframework.validation.Validator;
30

                  
13
New issues
154
						String filepath = name.substring(11);
155
						
156
						StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder".     NEW  
Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
157
						
158
						// If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
186
							}
187
							
188
							//if (outFile.getName().endsWith(".jsp") == false)
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
189
							//	outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);
190
							
194
							OpenmrsUtil.copyFile(inStream, outStream);
195
						}
196
					} else if (name.equals("moduleApplicationContext.xml") || name.equals("webModuleApplicationContext.xml")) {
Move the "moduleApplicationContext.xml" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Move the "webModuleApplicationContext.xml" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
197
						moduleNeedsContextRefresh = true;
198
					} else if (name.equals(mod.getModuleId() + "Context.xml")) {
294
			
295
			// additional checks on module needing a context refresh
296
			if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null && mod.getAdvicePoints().size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
Remove the literal "false" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
297
				
298
				// AOP advice points are only loaded during the context refresh now.
305
			// refresh the spring web context to get the just-created xml
306
			// files into it (if we copied an xml file)
307
			if (moduleNeedsContextRefresh && delayContextRefresh == false) {
Remove the literal "false" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
308
				if (log.isDebugEnabled()) {
309
					log.debug("Refreshing context for module" + mod);
355
			
356
			// return true if the module needs a context refresh and we didn't do it here
357
			return (moduleNeedsContextRefresh && delayContextRefresh == true);
Remove the literal "true" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
358
			
359
		}
482
			HttpServlet otherServletUsingSameName = moduleServlets.get(name);
483
			if (otherServletUsingSameName != null) {
484
				//log.debug("A servlet mapping with name " + name + " already exists. " + mod.getModuleId() + "'s servlet is overwriting it");
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
485
				String otherServletName = otherServletUsingSameName.getClass().getPackage() + "."
486
				        + otherServletUsingSameName.getClass().getName();
595
			for (Iterator<String> i = moduleFiltersByName.keySet().iterator(); i.hasNext();) {
596
				String filterName = i.next();
597
				Filter filterVal = moduleFiltersByName.get(filterName);
org.openmrs.module.web.WebModuleUtil.unloadFilters(Module) makes inefficient use of keySet iterator instead of entrySet iterator     NEW  
Performance - Inefficient use of keySet iterator instead of entrySet iterator
598
				if (filters.contains(filterVal)) {
599
					i.remove();
826
		}
827
		
828
		if (skipRefresh == false) {
Remove the literal "false" boolean value.     NEW  
Literal boolean values should not be used in condition expressions
829
			//try {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
830
			//	if (dispatcherServlet != null)
831
			//		dispatcherServlet.reInitFrameworkServlet();
966
			
967
			// Output to console for testing
968
			// StreamResult result = new StreamResult(System.out);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
969
			
970
			transformer.transform(source, result);
2
New issues
191
		
192
		// Match exact or full wildcard
193
		if (patternToCheck.equals("*") || patternToCheck.equals("/*") || patternToCheck.equals(requestPath)) {
Move the "*" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Move the "/*" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
194
			return true;
195
		}
2
New issues
46
		// refresh the application context to look for module xml config files as well
47
		
48
		//XmlWebApplicationContext wac = ((XmlWebApplicationContext)getWebApplicationContext());
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
49
		Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
50
		//wac.refresh();
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
51
		
52
		log.debug("Framework being initialized");
13
New issues
72
 * modules 2) Copy the custom look/images/messages over into the web layer
73
 */
74
public final class Listener extends ContextLoader implements ServletContextListener { // extends ContextLoaderListener {
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
Move this trailing comment on the previous empty line.     NEW  
Comments should not be located at the end of lines of code
75

                  
76
	protected final Log log = LogFactory.getLog(getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
77
	
78
	private static boolean runtimePropertiesFound = false;
137
	@Override
138
	public void contextInitialized(ServletContextEvent event) {
139
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
140
		
141
		log.debug("Starting the OpenMRS webapp");
183
				copyCustomizationIntoWebapp(servletContext, props);
184
				
185
				//super.contextInitialized(event);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
186
				// also see commented out line in contextDestroyed
187
				
232
		
233
		//Ensure that we are being called from WebDaemon
234
		//TODO this did not work because callerClass was org.openmrs.web.WebDaemon$1 instead of org.openmrs.web.WebDaemon
Complete the task associated to this TODO comment.     NEW  
"TODO" tags should be handled
235
		/*Class<?> callerClass = new OpenmrsSecurityManager().getCallerClass(0);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
236
		if (!WebDaemon.class.isAssignableFrom(callerClass))
237
			throw new APIException("This method can only be called from the WebDaemon class, not " + callerClass.getName());*/
353
	 */
354
	private void clearDWRFile(ServletContext servletContext) {
355
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
356
		
357
		String realPath = servletContext.getRealPath("");
408
	 */
409
	private void copyCustomizationIntoWebapp(ServletContext servletContext, Properties props) {
410
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
411
		
412
		String realPath = servletContext.getRealPath("");
472
	 */
473
	private boolean copyFile(String fromPath, String toPath) {
474
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
475
		
476
		FileInputStream inputStream = null;
514
	 */
515
	public static void loadBundledModules(ServletContext servletContext) {
516
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
517
		
518
		String path = servletContext.getRealPath("");
582
		
583
		// commented out because we are not init'ing it in the contextInitialization anymore
584
		// super.contextDestroyed(event);
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
585
		
586
		try {
640
	public static void performWebStartOfModules(Collection<Module> startedModules, ServletContext servletContext)
641
	        throws ModuleMustStartException, Exception {
642
		Log log = LogFactory.getLog(Listener.class);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
643
		
644
		boolean someModuleNeedsARefresh = false;
1
New issues
135
		
136
		// can't really do this because PropertyEditors are not told what type of class they are changing :-(
137
		//wdb.registerCustomEditor(OpenmrsObject.class, new OpenmrsObjectByUuidEditor());
This block of commented-out lines of code should be removed.     NEW  
Sections of code should not be "commented out"
138
	}
139
	
2
New issues
131
			    OpenmrsConstants.GLOBAL_PROPERTY_GZIP_ENABLED, "");
132
			
133
			boolean isEnabled = gzipEnabled.toLowerCase().equals("true");
Move the "true" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
Replace these toUpperCase()/toLowerCase() and equals() calls with a single equalsIgnoreCase() call.     NEW  
Case insensitive string comparisons should be made without intermediate upper or lower casing
134
			cachedGZipEnabledFlag = isEnabled;
135
			return cachedGZipEnabledFlag;
2
New issues
150
			} else {
151
				
152
				if (httpRequest.getMethod().equals("GET")) {
Move the "GET" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
153
					doGet(httpRequest, httpResponse);
154
				} else if (httpRequest.getMethod().equals("POST")) {
Move the "POST" string literal on the left side of this string comparison.     NEW  
Strings literals should be placed on the left side when checking for equality
155
					// only clear errors before POSTS so that redirects can show errors too.
156
					errors.clear();
4
New issues
84
public class InitializationFilter extends StartupFilter {
85
	
86
	private static final Log log = LogFactory.getLog(InitializationFilter.class);
Rename the "log" logger to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
87
	
88
	private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml";
1570
									        + RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form",
1571
									    wizardModel.remoteUsername, wizardModel.remotePassword);
1572
									if (inData == null) {
Redundant nullcheck of inData, which is known to be non-null in org.openmrs.web.filter.initialization.InitializationFilter$InitializationCompletion$1.run()     NEW  
Dodgy - Redundant nullcheck of value known to be non-null
1573
										reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, "");
1574
										return;
1590
									        + RELEASE_TESTING_MODULE_PATH + "getModules.htm", wizardModel.remoteUsername,
1591
									    wizardModel.remotePassword);
1592
									if (inModules == null) {
Redundant nullcheck of inModules, which is known to be non-null in org.openmrs.web.filter.initialization.InitializationFilter$InitializationCompletion$1.run()     NEW  
Dodgy - Redundant nullcheck of value known to be non-null
1593
										reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_FETCH_MODULES, DEFAULT_PAGE, "");
1594
										return;
1772
									Context.logout();
1773
								}
1774
								catch (ContextAuthenticationException ex) {
Either log or rethrow this exception.     NEW  
Exception handlers should preserve the original exception
1775
									log.info("No need to change admin password.");
1776
								}
2
New issues
10
package org.openmrs.web.filter.startuperror;
11

                  
12
import java.io.PrintWriter;
Remove this unused import 'java.io.PrintWriter'.     NEW  
Useless imports should be removed
13
import java.io.StringWriter;
Remove this unused import 'java.io.StringWriter'.     NEW  
Useless imports should be removed
14

                  
15
import org.apache.commons.lang.exception.ExceptionUtils;
16
New issues
66
public class UpdateFilter extends StartupFilter {
67
	
68
	protected final Log log = LogFactory.getLog(getClass());
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".     NEW  
Loggers should be "private static final" and should share a naming convention
69
	
70
	/**
169
				// allow current super user to review update progress
170
				if (isDatabaseUpdateInProgress) {
171
					referenceMap.put("updateJobStarted", true);
Define a constant instead of duplicating this literal "updateJobStarted" 3 times.     NEW  
String literals should not be duplicated
172
					httpResponse.setContentType("text/html");
173
					renderTemplate(REVIEW_CHANGES, referenceMap, httpResponse);
460
	 * @should return false if given user does not have the super user role
461
	 */
462
	protected boolean isSuperUser(Connection connection, Integer userId) throws Exception {
Define and throw a dedicated exception instead of using a generic one.     NEW  
Generic exceptions should never be thrown
463
		// the 'Administrator' part of this string is necessary because if the database was upgraded
464
		// by OpenMRS 1.6 alpha then System Developer was renamed to that. This has to be here so we
524
				} else {
525
					if (log.isDebugEnabled()) {
526
						log.debug("Setting updates required to " + (model.changes.size() > 0)
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
527
						        + " because of the size of unrun changes");
528
					}
529
					setUpdatesRequired(model.changes.size() > 0);
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
530
				}
531
			}
622
		private List<String> updateWarnings = new LinkedList<String>();
623
		
624
		synchronized public void reportError(String error, Object... params) {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
625
			Map<String, Object[]> errors = new HashMap<String, Object[]>();
626
			errors.put(error, params);
628
		}
629
		
630
		synchronized public void reportErrors(Map<String, Object[]> errs) {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
631
			errors.putAll(errs);
632
			erroneous = true;
633
		}
634
		
635
		synchronized public boolean hasErrors() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
636
			return erroneous;
637
		}
638
		
639
		synchronized public Map<String, Object[]> getErrors() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
640
			return errors;
641
		}
659
		}
660
		
661
		synchronized public void setMessage(String message) {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
662
			this.message = message;
663
		}
664
		
665
		synchronized public String getMessage() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
666
			return message;
667
		}
668
		
669
		synchronized public void addChangesetId(String changesetid) {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
670
			this.changesetIds.add(changesetid);
671
			this.executingChangesetId = changesetid;
672
		}
673
		
674
		synchronized public List<String> getChangesetIds() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
675
			return changesetIds;
676
		}
677
		
678
		synchronized public String getExecutingChangesetId() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
679
			return executingChangesetId;
680
		}
687
		}
688
		
689
		synchronized public boolean hasWarnings() {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
690
			return hasUpdateWarnings;
691
		}
692
		
693
		synchronized public void reportWarnings(List<String> warnings) {
Reorder the modifiers to comply with the Java Language Specification.     NEW  
Modifiers should be declared in the correct order
694
			updateWarnings.addAll(warnings);
695
			hasUpdateWarnings = true;
1
New issues
51
		
52
		try {
53
			if (changes != null && changes.size() > 0) {
Use isEmpty() to check whether the collection is empty or not.     NEW  
Collection.isEmpty() should be used to test for emptiness
54
				updateRequired = true;
55
			} else {