	/**
	 * Custom search endpoint that fetches encounters that include medication requests. NOTE: This query
	 * has been designed to provide the backend query functionality needed by the Dispensing ESM, and so
	 * the exact contract on what is returned may be modified as that ESM evolves. NOTE: requires Core
	 * 2.6.1 or higher (with new "declined" fulfiller status)
	 *
	 * @param date restrict by encounter date
	 * @param status if set to active, when determined encounters to include, exclude encounters that
	 *            *only* have completed, cancelled or declined medication requests
	 * @param patientSearchTerm restrict to encounters for patients who name or identifier matches the
	 *            search term
	 * @param location restrict to encounters at a certain location
	 * @return bundle that includes the medication requests and any medication dispenses that reference
	 *         those requests
	 */
	@Search(queryName = "encountersWithMedicationRequests")
	public IBundleProvider getEncountersWithMedicationRequestsSearch(
	        @OptionalParam(name = Encounter.SP_DATE) DateRangeParam date, @OptionalParam(name = "status") TokenParam status,
	        @OptionalParam(name = "patientSearchTerm") TokenParam patientSearchTerm,
	        @OptionalParam(name = "location") ReferenceAndListParam location) {

		EncounterSearchParams params = new EncounterSearchParams();

		// we always want encounters, not visits
		params.setTag(new TokenAndListParam()
		        .addAnd(new TokenParam().setSystem(OPENMRS_FHIR_EXT_ENCOUNTER_TAG).setValue("encounter")));

		if (date != null && !date.isEmpty()) {
			params.setDate(date);
		}

		if (status != null && !status.isEmpty() && status.getValue().equalsIgnoreCase("active")) {
			// encounter must have a medication request that is neither completed nor cancelled nor declined (expired is okay, since we are using another definition of expired for dispensing purposes)
			HasOrListParam notCompletedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "completed"));
			HasOrListParam notDeclinedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "declined"));
			HasOrListParam notCancelledHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "status:not", "cancelled"));
			params.setHasAndListParam(
			    new HasAndListParam().addAnd(notCancelledHasParam).addAnd(notDeclinedHasParam).addAnd(notCompletedHasParam));
		} else {
			// for "all" query only restriction is that the encounter has at least one medication request
			params.setHasAndListParam(new HasAndListParam()
			        .addAnd(new HasOrListParam().add(new HasParam("MedicationRequest", "encounter", "intent", "order"))));
		}

		// sort by date descending, so most recent is first
		SortSpec sortSpec = new SortSpec();
		sortSpec.setParamName("date");
		sortSpec.setOrder(SortOrderEnum.DESC);
		params.setSort(sortSpec);

		// search on identifier or patient name if that value has been passed in
		if (patientSearchTerm != null && !patientSearchTerm.isEmpty()) {
			ReferenceOrListParam subjectReference = new ReferenceOrListParam();
			subjectReference.add(new ReferenceParam("name", patientSearchTerm.getValue()));
			subjectReference.add(new ReferenceParam("identifier", patientSearchTerm.getValue()));
			params.setSubject(new ReferenceAndListParam().addAnd(subjectReference));
		}

		// search by location
		params.setLocation(location);

		// include all medication requests associated with the encounter, and then all dispenses associated with those requests
		HashSet<Include> revIncludes = new HashSet<>();
		Include medicationRequestInclude = new Include("MedicationRequest:encounter", false);
		Include medicationDispenseInclude = new Include("MedicationDispense:prescription", true);
		revIncludes.add(medicationRequestInclude);
		revIncludes.add(medicationDispenseInclude);
		params.setRevIncludes(revIncludes);

		return new SearchQueryBundleProviderR3Wrapper(encounterService.searchForEncounters(params));
	}

	/**
	 * Custom search endpoint that fetches encounters that include medication requests. NOTE: This query
	 * has been designed to provide the backend query functionality needed by the Dispensing ESM, and so
	 * the exact contract on what is returned may be modified as that ESM evolves. NOTE: requires Core
	 * 2.6.1 or higher (with new "declined" fulfiller status)
	 *
	 * @param date restrict by encounter date
	 * @param status if set to active, when determined encounters to include, exclude encounters that
	 *            *only* have completed, cancelled or declined medication requests
	 * @param patientSearchTerm restrict to encounters for patients who name or identifier matches the
	 *            search term
	 * @param location restrict to encounters at a certain location
	 * @return bundle that includes the medication requests and any medication dispenses that reference
	 *         those requests
	 */
	@Search(queryName = "encountersWithMedicationRequests")
	public IBundleProvider getEncountersWithMedicationRequestsSearch(
	        @OptionalParam(name = Encounter.SP_DATE) DateRangeParam date, @OptionalParam(name = "status") TokenParam status,
	        @OptionalParam(name = "patientSearchTerm") TokenParam patientSearchTerm,
	        @OptionalParam(name = "location") ReferenceAndListParam location) {

		EncounterSearchParams params = new EncounterSearchParams();

		// we always want encounters, not visits
		params.setTag(new TokenAndListParam()
		        .addAnd(new TokenParam().setSystem(OPENMRS_FHIR_EXT_ENCOUNTER_TAG).setValue("encounter")));

		if (date != null && !date.isEmpty()) {
			params.setDate(date);
		}

		if (status != null && !status.isEmpty() && status.getValue().equalsIgnoreCase("active")) {
			// encounter must have a medication request that is neither completed nor cancelled nor declined (expired is okay, since we are using another definition of expired for dispensing purposes)
			HasOrListParam notCompletedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "completed"));
			HasOrListParam notDeclinedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "declined"));
			HasOrListParam notCancelledHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "status:not", "cancelled"));
			params.setHasAndListParam(
			    new HasAndListParam().addAnd(notCancelledHasParam).addAnd(notDeclinedHasParam).addAnd(notCompletedHasParam));
		} else {
			// for "all" query only restriction is that the encounter has at least one medication request
			params.setHasAndListParam(new HasAndListParam()
			        .addAnd(new HasOrListParam().add(new HasParam("MedicationRequest", "encounter", "intent", "order"))));
		}

		// sort by date descending, so most recent is first
		SortSpec sortSpec = new SortSpec();
		sortSpec.setParamName("date");
		sortSpec.setOrder(SortOrderEnum.DESC);
		params.setSort(sortSpec);

		// search on identifier or patient name if that value has been passed in
		if (patientSearchTerm != null && !patientSearchTerm.isEmpty()) {
			ReferenceOrListParam subjectReference = new ReferenceOrListParam();
			subjectReference.add(new ReferenceParam("name", patientSearchTerm.getValue()));
			subjectReference.add(new ReferenceParam("identifier", patientSearchTerm.getValue()));
			params.setSubject(new ReferenceAndListParam().addAnd(subjectReference));
		}

		// search by location
		params.setLocation(location);

		// include all medication requests associated with the encounter, and then all dispenses associated with those requests
		HashSet<Include> revIncludes = new HashSet<Include>();
		Include medicationRequestInclude = new Include("MedicationRequest:encounter", false);
		Include medicationDispenseInclude = new Include("MedicationDispense:prescription", true);
		revIncludes.add(medicationRequestInclude);
		revIncludes.add(medicationDispenseInclude);
		params.setRevIncludes(revIncludes);

		return new SearchQueryBundleProviderR3Wrapper(encounterService.searchForEncounters(params));
	}

Replace Generic With Diamond HashSet<Include> with HashSet<> in method public getEncountersWithMedicationRequestsSearch(date DateRangeParam, status TokenParam, patientSearchTerm TokenParam, location ReferenceAndListParam) : IBundleProvider from class org.openmrs.module.fhir2.providers.r3.EncounterFhirResourceProvider


	/**
	 * Custom search endpoint that fetches encounters that include medication requests. NOTE: This query
	 * has been designed to provide the backend query functionality needed by the Dispensing ESM, and so
	 * the exact contract on what is returned may be modified as that ESM evolves. NOTE: requires Core
	 * 2.6.1 or higher (with new "declined" fulfiller status)
	 *
	 * @param date restrict by encounter date
	 * @param status if set to active, when determined encounters to include, exclude encounters that
	 *            *only* have completed, cancelled or declined medication requests
	 * @param patientSearchTerm restrict to encounters for patients who name or identifier matches the
	 *            search term
	 * @param location restrict to encounters at a certain location
	 * @return bundle that includes the medication requests and any medication dispenses that reference
	 *         those requests
	 */

	@Search(queryName = "encountersWithMedicationRequests")
	public IBundleProvider getEncountersWithMedicationRequestsSearch(
	        @OptionalParam(name = Encounter.SP_DATE) DateRangeParam date, @OptionalParam(name = "status") TokenParam status,
	        @OptionalParam(name = "patientSearchTerm") TokenParam patientSearchTerm,
	        @OptionalParam(name = "location") ReferenceAndListParam location) {

		EncounterSearchParams params = new EncounterSearchParams();

		// we always want encounters, not visits
		params.setTag(new TokenAndListParam()
		        .addAnd(new TokenParam().setSystem(OPENMRS_FHIR_EXT_ENCOUNTER_TAG).setValue("encounter")));

		if (date != null && !date.isEmpty()) {
			// encounter must be equal to or after the configured (expire) date
			params.setDate(date);
		}

		if (status != null && !status.isEmpty() && status.getValue().equalsIgnoreCase("active")) {
			// encounter must have a medication request that is neither completed nor cancelled nor declined (expired is okay, since we are using another definition of expired for dispensing purposes)
			HasOrListParam notCompletedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "completed"));
			HasOrListParam notDeclinedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "declined"));
			HasOrListParam notCancelledHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "status:not", "cancelled"));
			params.setHasAndListParam(
			    new HasAndListParam().addAnd(notCancelledHasParam).addAnd(notDeclinedHasParam).addAnd(notCompletedHasParam));
		} else {
			// for "all" query only restriction is that the encounter has at least one medication request
			params.setHasAndListParam(new HasAndListParam()
			        .addAnd(new HasOrListParam().add(new HasParam("MedicationRequest", "encounter", "intent", "order"))));
		}

		// sort by date descending, so most recent is first
		SortSpec sortSpec = new SortSpec();
		sortSpec.setParamName("date");
		sortSpec.setOrder(SortOrderEnum.DESC);
		params.setSort(sortSpec);

		// search on identifier or patient name if that value has been passed in
		if (patientSearchTerm != null && !patientSearchTerm.isEmpty()) {
			ReferenceOrListParam subjectReference = new ReferenceOrListParam();
			subjectReference.add(new ReferenceParam("name", patientSearchTerm.getValue()));
			subjectReference.add(new ReferenceParam("identifier", patientSearchTerm.getValue()));
			params.setSubject(new ReferenceAndListParam().addAnd(subjectReference));
		}

		// search by location
		params.setLocation(location);

		// include all medication requests associated with the encounter, and then all dispenses associated with those requests
		HashSet<Include> revIncludes = new HashSet<>();
		Include medicationRequestInclude = new Include("MedicationRequest:encounter", false);
		Include medicationDispenseInclude = new Include("MedicationDispense:prescription", true);
		revIncludes.add(medicationRequestInclude);
		revIncludes.add(medicationDispenseInclude);
		params.setRevIncludes(revIncludes);

		return encounterService.searchForEncounters(params);
	}

	/**
	 * Custom search endpoint that fetches encounters that include medication requests. NOTE: This query
	 * has been designed to provide the backend query functionality needed by the Dispensing ESM, and so
	 * the exact contract on what is returned may be modified as that ESM evolves. NOTE: requires Core
	 * 2.6.1 or higher (with new "declined" fulfiller status)
	 *
	 * @param date restrict by encounter date
	 * @param status if set to active, when determined encounters to include, exclude encounters that
	 *            *only* have completed, cancelled or declined medication requests
	 * @param patientSearchTerm restrict to encounters for patients who name or identifier matches the
	 *            search term
	 * @param location restrict to encounters at a certain location
	 * @return bundle that includes the medication requests and any medication dispenses that reference
	 *         those requests
	 */

	@Search(queryName = "encountersWithMedicationRequests")
	public IBundleProvider getEncountersWithMedicationRequestsSearch(
	        @OptionalParam(name = Encounter.SP_DATE) DateRangeParam date, @OptionalParam(name = "status") TokenParam status,
	        @OptionalParam(name = "patientSearchTerm") TokenParam patientSearchTerm,
	        @OptionalParam(name = "location") ReferenceAndListParam location) {

		EncounterSearchParams params = new EncounterSearchParams();

		// we always want encounters, not visits
		params.setTag(new TokenAndListParam()
		        .addAnd(new TokenParam().setSystem(OPENMRS_FHIR_EXT_ENCOUNTER_TAG).setValue("encounter")));

		if (date != null && !date.isEmpty()) {
			// encounter must be equal to or after the configured (expire) date
			params.setDate(date);
		}

		if (status != null && !status.isEmpty() && status.getValue().equalsIgnoreCase("active")) {
			// encounter must have a medication request that is neither completed nor cancelled nor declined (expired is okay, since we are using another definition of expired for dispensing purposes)
			HasOrListParam notCompletedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "completed"));
			HasOrListParam notDeclinedHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "fulfillerStatus:not", "declined"));
			HasOrListParam notCancelledHasParam = new HasOrListParam()
			        .add(new HasParam("MedicationRequest", "encounter", "status:not", "cancelled"));
			params.setHasAndListParam(
			    new HasAndListParam().addAnd(notCancelledHasParam).addAnd(notDeclinedHasParam).addAnd(notCompletedHasParam));
		} else {
			// for "all" query only restriction is that the encounter has at least one medication request
			params.setHasAndListParam(new HasAndListParam()
			        .addAnd(new HasOrListParam().add(new HasParam("MedicationRequest", "encounter", "intent", "order"))));
		}

		// sort by date descending, so most recent is first
		SortSpec sortSpec = new SortSpec();
		sortSpec.setParamName("date");
		sortSpec.setOrder(SortOrderEnum.DESC);
		params.setSort(sortSpec);

		// search on identifier or patient name if that value has been passed in
		if (patientSearchTerm != null && !patientSearchTerm.isEmpty()) {
			ReferenceOrListParam subjectReference = new ReferenceOrListParam();
			subjectReference.add(new ReferenceParam("name", patientSearchTerm.getValue()));
			subjectReference.add(new ReferenceParam("identifier", patientSearchTerm.getValue()));
			params.setSubject(new ReferenceAndListParam().addAnd(subjectReference));
		}

		// search by location
		params.setLocation(location);

		// include all medication requests associated with the encounter, and then all dispenses associated with those requests
		HashSet<Include> revIncludes = new HashSet<Include>();
		Include medicationRequestInclude = new Include("MedicationRequest:encounter", false);
		Include medicationDispenseInclude = new Include("MedicationDispense:prescription", true);
		revIncludes.add(medicationRequestInclude);
		revIncludes.add(medicationDispenseInclude);
		params.setRevIncludes(revIncludes);

		return encounterService.searchForEncounters(params);
	}

Replace Generic With Diamond HashSet<Include> with HashSet<> in method public getEncountersWithMedicationRequestsSearch(date DateRangeParam, status TokenParam, patientSearchTerm TokenParam, location ReferenceAndListParam) : IBundleProvider from class org.openmrs.module.fhir2.providers.r4.EncounterFhirResourceProvider


	@Test
	public void shouldTranslateConceptSetToValueSet() {
		ConceptName conceptName = new ConceptName();
		conceptName.setName("test");

		ConceptDescription description = new ConceptDescription();
		description.setDescription("test");

		when(concept.getUuid()).thenReturn(CONCEPT_UUID);
		when(concept.getName()).thenReturn(conceptName);
		when(concept.getDateChanged()).thenReturn(new Date());
		when(concept.getSet()).thenReturn(true);

		Concept concept1 = new Concept();
		ConceptMap conceptMap = mock(ConceptMap.class);
		ConceptReferenceTerm conceptReferenceTerm = mock(ConceptReferenceTerm.class);
		ConceptSource conceptSource = mock(ConceptSource.class);

		when(conceptMap.getConceptReferenceTerm()).thenReturn(conceptReferenceTerm);
		when(conceptReferenceTerm.getConceptSource()).thenReturn(conceptSource);
		when(conceptReferenceTerm.getCode()).thenReturn("1000-1");
		when(conceptSource.getName()).thenReturn("LOINC");
		concept1.addConceptMapping(conceptMap);

		FhirConceptSource loinc = new FhirConceptSource();
		ConceptSource loincConceptSource = new ConceptSource();
		loincConceptSource.setName("LOINC");
		loinc.setConceptSource(loincConceptSource);
		loinc.setUrl(FhirTestConstants.LOINC_SYSTEM_URL);
		when(conceptSourceService.getFhirConceptSource(loincConceptSource)).thenReturn(Optional.of(loinc));

		ConceptSet conceptSet = new ConceptSet();
		conceptSet.setConceptSet(concept);
		conceptSet.setConcept(concept1);

		Collection<ConceptSet> conceptSets = new ArrayList<>();
		conceptSets.add(conceptSet);

		when(concept.getConceptSets()).thenReturn(conceptSets);

		ValueSet valueSet = valueSetTranslator.toFhirResource(concept);

		assertThat(valueSet.getId(), equalTo(CONCEPT_UUID));
		assertThat(valueSet.getCompose(), notNullValue());
		assertThat(valueSet.getCompose().getInclude(), hasSize(greaterThanOrEqualTo(1)));
		assertThat((valueSet.getCompose().getInclude().iterator().next()).getSystemElement(), notNullValue());
		assertThat(((valueSet.getCompose().getInclude().iterator().next()).getConcept().iterator().next()).getCode(),
		    notNullValue());
	}

	@Test
	public void shouldTranslateConceptSetToValueSet() {
		ConceptName conceptName = new ConceptName();
		conceptName.setName("test");

		ConceptDescription description = new ConceptDescription();
		description.setDescription("test");

		when(concept.getUuid()).thenReturn(CONCEPT_UUID);
		when(concept.getName()).thenReturn(conceptName);
		when(concept.getDateChanged()).thenReturn(new Date());
		when(concept.getSet()).thenReturn(true);

		Concept concept1 = new Concept();
		ConceptMap conceptMap = mock(ConceptMap.class);
		ConceptReferenceTerm conceptReferenceTerm = mock(ConceptReferenceTerm.class);
		ConceptSource conceptSource = mock(ConceptSource.class);

		when(conceptMap.getConceptReferenceTerm()).thenReturn(conceptReferenceTerm);
		when(conceptReferenceTerm.getConceptSource()).thenReturn(conceptSource);
		when(conceptReferenceTerm.getCode()).thenReturn("1000-1");
		when(conceptSource.getName()).thenReturn("LOINC");
		concept1.addConceptMapping(conceptMap);

		FhirConceptSource loinc = new FhirConceptSource();
		ConceptSource loincConceptSource = new ConceptSource();
		loincConceptSource.setName("LOINC");
		loinc.setConceptSource(loincConceptSource);
		loinc.setUrl(FhirTestConstants.LOINC_SYSTEM_URL);
		when(conceptSourceService.getFhirConceptSource(loincConceptSource)).thenReturn(Optional.of(loinc));

		ConceptSet conceptSet = new ConceptSet();
		conceptSet.setConceptSet(concept);
		conceptSet.setConcept(concept1);

		Collection<ConceptSet> conceptSets = new ArrayList<ConceptSet>();
		conceptSets.add(conceptSet);

		when(concept.getConceptSets()).thenReturn(conceptSets);

		ValueSet valueSet = valueSetTranslator.toFhirResource(concept);

		assertThat(valueSet.getId(), equalTo(CONCEPT_UUID));
		assertThat(valueSet.getCompose(), notNullValue());
		assertThat(valueSet.getCompose().getInclude(), hasSize(greaterThanOrEqualTo(1)));
		assertThat((valueSet.getCompose().getInclude().iterator().next()).getSystemElement(), notNullValue());
		assertThat(((valueSet.getCompose().getInclude().iterator().next()).getConcept().iterator().next()).getCode(),
		    notNullValue());
	}

Replace Generic With Diamond ArrayList<ConceptSet> with ArrayList<> in method public shouldTranslateConceptSetToValueSet() : void from class org.openmrs.module.fhir2.api.translators.impl.ValueSetTranslatorImplTest


    public static List<String> createStatsSortedByKD(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "K/D",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return (double) stats.kills() / stats.deaths();
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByKD(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "K/D", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return (double) stats.kills() / stats.deaths();
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, provider);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByKD(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    public static List<String> createStatsSortedByKPR(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "KPR",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return (double) stats.kills() / stats.totalRoundsPlayed();
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByKPR(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "KPR", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return (double) stats.kills() / stats.totalRoundsPlayed();
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, DataUtils.StatsProvider.OVER_OR_5_MATCHES);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByKPR(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    public static List<String> createStatsSortedByADR(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "ADR",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return stats.adr();
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByADR(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "ADR", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return stats.adr();
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, DataUtils.StatsProvider.OVER_OR_5_MATCHES);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByADR(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    public static List<String> createStatsSortedByKAST(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "KAST",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return stats.kast();
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByKAST(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "KAST", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return stats.kast();
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, DataUtils.StatsProvider.OVER_OR_5_MATCHES);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByKAST(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    public static List<String> createStatsSortedByHLTV(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "HLTV",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return stats.hltvRating();
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByHLTV(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "HLTV", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return stats.hltvRating();
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, DataUtils.StatsProvider.OVER_OR_5_MATCHES);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByHLTV(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    public static List<String> createStatsSortedByHeadshotPercent(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(
                DataUtils.getAllSinglePlayerStats(dataContainer),
                "HS%",
                new DataUtils.ValueProvider<>() {
                    @Override
                    public Double getValue(SinglePlayerStats stats) {
                        return stats.kills() > 0 ? ((double) stats.headshotKills() / stats.kills()) * 100 : 0.0;
                    }

                    @Override
                    public boolean reversed() {
                        return true;
                    }
                },
                provider);
    }

    public static List<String> createStatsSortedByHeadshotPercent(DataContainer dataContainer) {
        return DataUtils.formatForSortedPlayerStats(DataUtils.getAllSinglePlayerStats(dataContainer), "HS%%", new DataUtils.ValueProvider<SinglePlayerStats, Double>() {
            @Override
            public Double getValue(SinglePlayerStats stats) {
                return (double) stats.headshotKills() / stats.kills() * 100;
            }

            @Override
            public boolean reversed() {
                return true;
            }

        }, DataUtils.StatsProvider.OVER_OR_5_MATCHES);
    }

Replace Generic With Diamond DataUtils.ValueProvider<SinglePlayerStats,Double> with DataUtils.ValueProvider<> in method public createStatsSortedByHeadshotPercent(dataContainer DataContainer) : List<String> from class utils.DataFormatter


    /**
     * Schedules the execution of a job for computing a snapshot for a budget for a selected year and month.
     *
     * @param key the budget key.
     * @param year the reference year.
     * @param month the reference month.
     */
    @Override
    public void scheduleSnapshotCreation(UUID key, int year, int month) {
        Map<String, String> jobParameters = new HashMap<>();

        // Set budget key
        String parameterKey = BudgetProcessingJobBuilder.STEP_BUDGET_PROCESSING +
                              Constants.PARAMETER_NAME_DELIMITER +
                              BudgetProcessingTask.EnumInParameter.BUDGET_KEY.getValue();
        String parameterValue = key.toString();
        jobParameters.put(parameterKey, parameterValue);

        // Set reference date
        parameterKey = BudgetProcessingJobBuilder.STEP_BUDGET_PROCESSING +
                       Constants.PARAMETER_NAME_DELIMITER +
                       BudgetProcessingTask.EnumInParameter.REFERENCE_DATE.getValue();
        parameterValue = String.format("%d%02d01", year, month);
        jobParameters.put(parameterKey, parameterValue);

        schedulerService.launch(BudgetProcessingJobBuilder.JOB_NAME, jobParameters);
    }

    /**
     * Schedules the execution of a job for computing a snapshot for a budget for a selected year and month.
     *
     * @param key the budget key.
     * @param year the reference year.
     * @param month the reference month.
     */
    @Override
    public void scheduleSnapshotCreation(UUID key, int year, int month) {
        Map<String, String> jobParameters = new HashMap<String, String>();

        // Set budget key
        String parameterKey = BudgetProcessingJobBuilder.STEP_BUDGET_PROCESSING +
                              Constants.PARAMETER_NAME_DELIMITER +
                              BudgetProcessingTask.EnumInParameter.BUDGET_KEY.getValue();
        String parameterValue = key.toString();
        jobParameters.put(parameterKey, parameterValue);

        // Set reference date
        parameterKey = BudgetProcessingJobBuilder.STEP_BUDGET_PROCESSING +
                       Constants.PARAMETER_NAME_DELIMITER +
                       BudgetProcessingTask.EnumInParameter.REFERENCE_DATE.getValue();
        parameterValue = String.format("%d%02d01", year, month);
        jobParameters.put(parameterKey, parameterValue);

        schedulerService.launch(BudgetProcessingJobBuilder.JOB_NAME, jobParameters);
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public scheduleSnapshotCreation(key UUID, year int, month int) : void from class eu.daiad.web.service.savings.DefaultBudgetService


    /**
     * Gets all active budgets.
     *
     * @return a list of {@link Budget}.
     */
    @Override
    public List<Budget> findActive() {
        List<Budget> result = new ArrayList<>();

        try {
            for (BudgetEntity entity : budgetRepository.getActiveBudgets()) {
                result.add(new Budget(entity, objectMapper));
            }
        } catch (IOException e) {
            throw createApplicationException(SavingsPotentialErrorCode.PARSE_ERROR);
        }

        return result;
    }

    /**
     * Gets all active budgets.
     *
     * @return a list of {@link Budget}.
     */
    @Override
    public List<Budget> findActive() {
        List<Budget> result = new ArrayList<Budget>();

        try {
            for (BudgetEntity entity : budgetRepository.getActiveBudgets()) {
                result.add(new Budget(entity, objectMapper));
            }
        } catch (IOException e) {
            throw createApplicationException(SavingsPotentialErrorCode.PARSE_ERROR);
        }

        return result;
    }

Replace Generic With Diamond ArrayList<Budget> with ArrayList<> in method public findActive() : List<Budget> from class eu.daiad.web.service.savings.DefaultBudgetService


    /**
     * Gets all pending budget snapshots.
     *
     * @return a list of {@link BudgetSnapshot}.
     */
    @Override
    public List<BudgetSnapshot> findPendingSnapshots() {
        List<BudgetSnapshot> snapshots = new ArrayList<>();

        for (BudgetSnapshotEntity entity : budgetRepository.findPendingSnapshots()) {
            snapshots.add(new BudgetSnapshot(entity));
        }

        return snapshots;
    }

    /**
     * Gets all pending budget snapshots.
     *
     * @return a list of {@link BudgetSnapshot}.
     */
    @Override
    public List<BudgetSnapshot> findPendingSnapshots() {
        List<BudgetSnapshot> snapshots = new ArrayList<BudgetSnapshot>();

        for (BudgetSnapshotEntity entity : budgetRepository.findPendingSnapshots()) {
            snapshots.add(new BudgetSnapshot(entity));
        }

        return snapshots;
    }

Replace Generic With Diamond ArrayList<BudgetSnapshot> with ArrayList<> in method public findPendingSnapshots() : List<BudgetSnapshot> from class eu.daiad.web.service.savings.DefaultBudgetService


    /**
     * Creates a new savings potential scenario
     *
     * @param user the owner.
     * @param name a user-friendly name for the scenario.
     * @param parameters parameters for selecting user data.
     * @return the new scenario key.
     */
    @Override
    public UUID create(AuthenticatedUser user, String name, TemporalSavingsConsumerSelectionFilter parameters) {
        UUID key;
        try {
            key = savingsPotentialRepository.create(user.getId(), name, parameters);

            Map<String, String> jobParameters = new HashMap<>();

            // Set execution mode to SAVINGS
            String parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                                  SavingsPotentialJobBuilder.EnumJobInParameter.MODE.getValue();
            String parameterValue = SavingsPotentialJobBuilder.MODE_SAVINGS;
            jobParameters.put(parameterKey, parameterValue);

            // Set scenario key
            parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                           SavingsPotentialJobBuilder.EnumJobInParameter.SCENARIO_KEY.getValue();
            parameterValue = key.toString();
            jobParameters.put(parameterKey, parameterValue);

            schedulerService.launch("SAVINGS-POTENTIAL", jobParameters);
        } catch(Exception ex) {
            throw wrapApplicationException(ex, SavingsPotentialErrorCode.CREATION_FAILED);
        }

        return key;
    }

    /**
     * Creates a new savings potential scenario
     *
     * @param user the owner.
     * @param name a user-friendly name for the scenario.
     * @param parameters parameters for selecting user data.
     * @return the new scenario key.
     */
    @Override
    public UUID create(AuthenticatedUser user, String name, TemporalSavingsConsumerSelectionFilter parameters) {
        UUID key;
        try {
            key = savingsPotentialRepository.create(user.getId(), name, parameters);

            Map<String, String> jobParameters = new HashMap<String, String>();

            // Set execution mode to SAVINGS
            String parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                                  SavingsPotentialJobBuilder.EnumJobInParameter.MODE.getValue();
            String parameterValue = SavingsPotentialJobBuilder.MODE_SAVINGS;
            jobParameters.put(parameterKey, parameterValue);

            // Set scenario key
            parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                           SavingsPotentialJobBuilder.EnumJobInParameter.SCENARIO_KEY.getValue();
            parameterValue = key.toString();
            jobParameters.put(parameterKey, parameterValue);

            schedulerService.launch("SAVINGS-POTENTIAL", jobParameters);
        } catch(Exception ex) {
            throw wrapApplicationException(ex, SavingsPotentialErrorCode.CREATION_FAILED);
        }

        return key;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public create(user AuthenticatedUser, name String, parameters TemporalSavingsConsumerSelectionFilter) : UUID from class eu.daiad.web.service.savings.DefaultSavingsPotentialService


    /**
     * Schedules a new job for computing the savings potential scenario results.
     *
     * @param key the scenario key.
     */
    @Override
    public void refresh(UUID key) {
        AuthenticatedUser user = getAuthenticatedUser();
        SavingsPotentialScenarioEntity entity = savingsPotentialRepository.getScenarioByKey(key);

        if ((user != null) && (user.getId() != entity.getOwner().getId())) {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION);
        }

        try {
            savingsPotentialRepository.reset(key);

            Map<String, String> jobParameters = new HashMap<>();

            // Set execution mode to SAVINGS
            String parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                                  SavingsPotentialJobBuilder.EnumJobInParameter.MODE.getValue();
            String parameterValue = SavingsPotentialJobBuilder.MODE_SAVINGS;
            jobParameters.put(parameterKey, parameterValue);

            // Set scenario key
            parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                           SavingsPotentialJobBuilder.EnumJobInParameter.SCENARIO_KEY.getValue();
            parameterValue = key.toString();
            jobParameters.put(parameterKey, parameterValue);

            schedulerService.launch("SAVINGS-POTENTIAL", jobParameters);
        } catch(Exception ex) {
            throw wrapApplicationException(ex, SavingsPotentialErrorCode.CREATION_FAILED);
        }
    }

    /**
     * Schedules a new job for computing the savings potential scenario results.
     *
     * @param key the scenario key.
     */
    @Override
    public void refresh(UUID key) {
        AuthenticatedUser user = getAuthenticatedUser();
        SavingsPotentialScenarioEntity entity = savingsPotentialRepository.getScenarioByKey(key);

        if ((user != null) && (user.getId() != entity.getOwner().getId())) {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION);
        }

        try {
            savingsPotentialRepository.reset(key);

            Map<String, String> jobParameters = new HashMap<String, String>();

            // Set execution mode to SAVINGS
            String parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                                  SavingsPotentialJobBuilder.EnumJobInParameter.MODE.getValue();
            String parameterValue = SavingsPotentialJobBuilder.MODE_SAVINGS;
            jobParameters.put(parameterKey, parameterValue);

            // Set scenario key
            parameterKey = Constants.PARAMETER_NAME_DELIMITER +
                           SavingsPotentialJobBuilder.EnumJobInParameter.SCENARIO_KEY.getValue();
            parameterValue = key.toString();
            jobParameters.put(parameterKey, parameterValue);

            schedulerService.launch("SAVINGS-POTENTIAL", jobParameters);
        } catch(Exception ex) {
            throw wrapApplicationException(ex, SavingsPotentialErrorCode.CREATION_FAILED);
        }
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public refresh(key UUID) : void from class eu.daiad.web.service.savings.DefaultSavingsPotentialService


    /**
     * Converts an instance of {@link AccountEntity} to an instance of {@link AuthenticatedUser}.
     *
     * @param entity an instance of {@link AccountEntity}.
     * @return a new instance of {@link AuthenticatedUser}.
     */
    private AuthenticatedUser accountEntityToUser(AccountEntity entity) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (AccountRoleEntity r : entity.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(r.getRole().getName()));
        }

        AuthenticatedUser user = new AuthenticatedUser(entity.getId(),
                                                       entity.getKey(),
                                                       entity.getUsername(),
                                                       entity.getPassword(),
                                                       entity.getUtility().getId(),
                                                       entity.getUtility().getKey(),
                                                       entity.isLocked(),
                                                       authorities);

        user.setCreatedOn(entity.getCreatedOn());
        user.setBirthdate(entity.getBirthdate());
        user.setCountry(entity.getCountry());
        user.setLocale(entity.getLocale());
        user.setFirstname(entity.getFirstname());
        user.setLastname(entity.getLastname());
        user.setGender(entity.getGender());
        user.setPostalCode(entity.getPostalCode());
        user.setTimezone(entity.getTimezone());
        user.setAllowPasswordReset(entity.isAllowPasswordReset());

        user.setWebMode(EnumWebMode.fromInteger(entity.getProfile().getWebMode()));
        user.setMobileMode(EnumMobileMode.fromInteger(entity.getProfile().getMobileMode()));
        user.setUtilityMode(EnumUtilityMode.fromInteger(entity.getProfile().getUtilityMode()));

        for(AccountUtilityEntity accountUtility : entity.getUtilities()) {
            user.getUtilities().add(accountUtility.getUtility().getId());
        }

        return user;
    }

    /**
     * Converts an instance of {@link AccountEntity} to an instance of {@link AuthenticatedUser}.
     *
     * @param entity an instance of {@link AccountEntity}.
     * @return a new instance of {@link AuthenticatedUser}.
     */
    private AuthenticatedUser accountEntityToUser(AccountEntity entity) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (AccountRoleEntity r : entity.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(r.getRole().getName()));
        }

        AuthenticatedUser user = new AuthenticatedUser(entity.getId(),
                                                       entity.getKey(),
                                                       entity.getUsername(),
                                                       entity.getPassword(),
                                                       entity.getUtility().getId(),
                                                       entity.getUtility().getKey(),
                                                       entity.isLocked(),
                                                       authorities);

        user.setCreatedOn(entity.getCreatedOn());
        user.setBirthdate(entity.getBirthdate());
        user.setCountry(entity.getCountry());
        user.setLocale(entity.getLocale());
        user.setFirstname(entity.getFirstname());
        user.setLastname(entity.getLastname());
        user.setGender(entity.getGender());
        user.setPostalCode(entity.getPostalCode());
        user.setTimezone(entity.getTimezone());
        user.setAllowPasswordReset(entity.isAllowPasswordReset());

        user.setWebMode(EnumWebMode.fromInteger(entity.getProfile().getWebMode()));
        user.setMobileMode(EnumMobileMode.fromInteger(entity.getProfile().getMobileMode()));
        user.setUtilityMode(EnumUtilityMode.fromInteger(entity.getProfile().getUtilityMode()));

        for(AccountUtilityEntity accountUtility : entity.getUtilities()) {
            user.getUtilities().add(accountUtility.getUtility().getId());
        }

        return user;
    }

Replace Generic With Diamond ArrayList<GrantedAuthority> with ArrayList<> in method private accountEntityToUser(entity AccountEntity) : AuthenticatedUser from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get account activity.
     *
     * @return a list with all the users.
     */
    @Override
    public List<AccountActivity> getAccountActivity() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        AuthenticatedUser user = null;

        if (auth.getPrincipal() instanceof AuthenticatedUser) {
            user = (AuthenticatedUser) auth.getPrincipal();
        }

        if (user != null) {
            return this.getAccountActivity(user.getUtilities());
        }

        return new ArrayList<>();
    }

    /**
     * Get account activity.
     *
     * @return a list with all the users.
     */
    @Override
    public List<AccountActivity> getAccountActivity() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        AuthenticatedUser user = null;

        if (auth.getPrincipal() instanceof AuthenticatedUser) {
            user = (AuthenticatedUser) auth.getPrincipal();
        }

        if (user != null) {
            return this.getAccountActivity(user.getUtilities());
        }

        return new ArrayList<AccountActivity>();
    }

Replace Generic With Diamond ArrayList<AccountActivity> with ArrayList<> in method public getAccountActivity() : List<AccountActivity> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get account activity for the users of the given utilities.
     *
     * @param utilities the ids of the utilities.
     * @return a list of the users for the given utility.
     */
    public List<AccountActivity> getAccountActivity(List<Integer> utilities) {
        String activityQueryString = "select a from trial_account_activity a where a.utilityId in :utilities order by a.username";

        TypedQuery<AccountActivityEntity> query = entityManager.createQuery(activityQueryString, AccountActivityEntity.class);

        query.setParameter("utilities", utilities);

        ArrayList<AccountActivity> results = new ArrayList<>();

        for (AccountActivityEntity a : query.getResultList()) {
            AccountActivity account = new AccountActivity();

            account.setId(a.getId());
            account.setKey(a.getKey());
            account.setUtilityId(a.getUtilityId());
            account.setAccountId(a.getAccountId());
            account.setAccountRegisteredOn(a.getAccountRegisteredOn() != null ? a.getAccountRegisteredOn().getMillis() : null);
            account.setUtilityName(a.getUtilityName());
            account.setUsername(a.getUsername());
            account.setFirstName(a.getFirstName());
            account.setLastName(a.getLastName());

            account.setNumberOfAmphiroDevices(a.getNumberOfAmphiroDevices());
            account.setNumberOfMeters(a.getNumberOfMeters());

            account.setLastDataUploadFailure((a.getLastDataUploadFailure() != null) ? a.getLastDataUploadFailure().getMillis() : null);
            account.setLastDataUploadSuccess(a.getLastDataUploadSuccess() != null ? a.getLastDataUploadSuccess().getMillis() : null);
            account.setLastLoginFailure(a.getLastLoginFailure() != null ? a.getLastLoginFailure().getMillis() : null);
            account.setLastLoginSuccess(a.getLastLoginSuccess() != null ? a.getLastLoginSuccess().getMillis() : null);
            account.setLeastAmphiroRegistration(a.getLeastAmphiroRegistration() != null ? a.getLeastAmphiroRegistration().getMillis() : null);
            account.setLeastMeterRegistration(a.getLeastMeterRegistration() != null ? a.getLeastMeterRegistration().getMillis() : null);

            account.setTransmissionCount(a.getTransmissionCount());
            account.setTransmissionIntervalMax(a.getTransmissionIntervalMax());
            account.setTransmissionIntervalSum(a.getTransmissionIntervalSum());

            results.add(account);
        }

        return results;
    }

    /**
     * Get account activity for the users of the given utilities.
     *
     * @param utilities the ids of the utilities.
     * @return a list of the users for the given utility.
     */
    public List<AccountActivity> getAccountActivity(List<Integer> utilities) {
        String activityQueryString = "select a from trial_account_activity a where a.utilityId in :utilities order by a.username";

        TypedQuery<AccountActivityEntity> query = entityManager.createQuery(activityQueryString, AccountActivityEntity.class);

        query.setParameter("utilities", utilities);

        ArrayList<AccountActivity> results = new ArrayList<AccountActivity>();

        for (AccountActivityEntity a : query.getResultList()) {
            AccountActivity account = new AccountActivity();

            account.setId(a.getId());
            account.setKey(a.getKey());
            account.setUtilityId(a.getUtilityId());
            account.setAccountId(a.getAccountId());
            account.setAccountRegisteredOn(a.getAccountRegisteredOn() != null ? a.getAccountRegisteredOn().getMillis() : null);
            account.setUtilityName(a.getUtilityName());
            account.setUsername(a.getUsername());
            account.setFirstName(a.getFirstName());
            account.setLastName(a.getLastName());

            account.setNumberOfAmphiroDevices(a.getNumberOfAmphiroDevices());
            account.setNumberOfMeters(a.getNumberOfMeters());

            account.setLastDataUploadFailure((a.getLastDataUploadFailure() != null) ? a.getLastDataUploadFailure().getMillis() : null);
            account.setLastDataUploadSuccess(a.getLastDataUploadSuccess() != null ? a.getLastDataUploadSuccess().getMillis() : null);
            account.setLastLoginFailure(a.getLastLoginFailure() != null ? a.getLastLoginFailure().getMillis() : null);
            account.setLastLoginSuccess(a.getLastLoginSuccess() != null ? a.getLastLoginSuccess().getMillis() : null);
            account.setLeastAmphiroRegistration(a.getLeastAmphiroRegistration() != null ? a.getLeastAmphiroRegistration().getMillis() : null);
            account.setLeastMeterRegistration(a.getLeastMeterRegistration() != null ? a.getLeastMeterRegistration().getMillis() : null);

            account.setTransmissionCount(a.getTransmissionCount());
            account.setTransmissionIntervalMax(a.getTransmissionIntervalMax());
            account.setTransmissionIntervalSum(a.getTransmissionIntervalSum());

            results.add(account);
        }

        return results;
    }

Replace Generic With Diamond ArrayList<AccountActivity> with ArrayList<> in method public getAccountActivity(utilities List<Integer>) : List<AccountActivity> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Searches users by user name prefix.
     *
     * @param prefix the prefix used for filtering users.
     * @return a list of users.
     */
    @Override
    public List<UserInfo> filterUserByPrefix(String prefix) {
        List<UserInfo> accounts = new ArrayList<>();

        String accountQueryString = "select a from account a " +
                                    "where (lower(a.firstname) like lower(:prefix) or lower(a.lastname) like lower(:prefix)) and " +
                                    "      (a.utility.id = :utility_id)";

        TypedQuery<AccountEntity> accountQuery = entityManager.createQuery(accountQueryString, AccountEntity.class)
                                                              .setMaxResults(100);

        accountQuery.setParameter("prefix", prefix + '%');
        accountQuery.setParameter("utility_id", getCurrentUtilityId());

        for (AccountEntity account : accountQuery.getResultList()) {
            accounts.add(new UserInfo(account));
        }

        return accounts;
    }

    /**
     * Searches users by user name prefix.
     *
     * @param prefix the prefix used for filtering users.
     * @return a list of users.
     */
    @Override
    public List<UserInfo> filterUserByPrefix(String prefix) {
        List<UserInfo> accounts = new ArrayList<UserInfo>();

        String accountQueryString = "select a from account a " +
                                    "where (lower(a.firstname) like lower(:prefix) or lower(a.lastname) like lower(:prefix)) and " +
                                    "      (a.utility.id = :utility_id)";

        TypedQuery<AccountEntity> accountQuery = entityManager.createQuery(accountQueryString, AccountEntity.class)
                                                              .setMaxResults(100);

        accountQuery.setParameter("prefix", prefix + '%');
        accountQuery.setParameter("utility_id", getCurrentUtilityId());

        for (AccountEntity account : accountQuery.getResultList()) {
            accounts.add(new UserInfo(account));
        }

        return accounts;
    }

Replace Generic With Diamond ArrayList<UserInfo> with ArrayList<> in method public filterUserByPrefix(prefix String) : List<UserInfo> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get the unique user keys for a given user group key.
     *
     * @param groupKey the user group key.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForGroup(UUID groupKey) {
        ArrayList<UUID> result = new ArrayList<>();
        try {
            Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from \"group\" g "
                            + "inner join group_member gm on g.id = gm.group_id "
                            + "inner join account a on gm.account_id = a.id where g.key = CAST(? as uuid)");
            query.setParameter(1, groupKey.toString());

            List<?> keys = query.getResultList();
            for (Object key : keys) {
                result.add(UUID.fromString((String) key));
            }
        } catch (Exception ex) {
            logger.error(String.format("Failed to load user keys for group [%s].", groupKey), ex);
        }

        return result;
    }

    /**
     * Get the unique user keys for a given user group key.
     *
     * @param groupKey the user group key.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForGroup(UUID groupKey) {
        ArrayList<UUID> result = new ArrayList<UUID>();
        try {
            Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from \"group\" g "
                            + "inner join group_member gm on g.id = gm.group_id "
                            + "inner join account a on gm.account_id = a.id where g.key = CAST(? as uuid)");
            query.setParameter(1, groupKey.toString());

            List<?> keys = query.getResultList();
            for (Object key : keys) {
                result.add(UUID.fromString((String) key));
            }
        } catch (Exception ex) {
            logger.error(String.format("Failed to load user keys for group [%s].", groupKey), ex);
        }

        return result;
    }

Replace Generic With Diamond ArrayList<UUID> with ArrayList<> in method public getUserKeysForGroup(groupKey UUID) : List<UUID> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get the unique user keys for a given utility key.
     *
     * @param utilityKey the utility key.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility(UUID utilityKey) {
        ArrayList<UUID> result = new ArrayList<>();
        try {
            Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from utility u "
                            + "inner join account a on u.id = a.utility_id where u.key = CAST(? as uuid)");
            query.setParameter(1, utilityKey.toString());

            List<?> keys = query.getResultList();
            for (Object key : keys) {
                result.add(UUID.fromString((String) key));
            }
        } catch (Exception ex) {
            logger.error(String.format("Failed to load user keys for utility [%s]", utilityKey), ex);
        }

        return result;
    }

    /**
     * Get the unique user keys for a given utility key.
     *
     * @param utilityKey the utility key.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility(UUID utilityKey) {
        ArrayList<UUID> result = new ArrayList<UUID>();
        try {
            Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from utility u "
                            + "inner join account a on u.id = a.utility_id where u.key = CAST(? as uuid)");
            query.setParameter(1, utilityKey.toString());

            List<?> keys = query.getResultList();
            for (Object key : keys) {
                result.add(UUID.fromString((String) key));
            }
        } catch (Exception ex) {
            logger.error(String.format("Failed to load user keys for utility [%s]", utilityKey), ex);
        }

        return result;
    }

Replace Generic With Diamond ArrayList<UUID> with ArrayList<> in method public getUserKeysForUtility(utilityKey UUID) : List<UUID> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get the unique user keys for a given utility id.
     *
     * @param utilityId the utility id.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility(int utilityId) {
        ArrayList<UUID> result = new ArrayList<>();

        Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from utility u "
                        + "inner join account a on u.id = a.utility_id where u.id = :utilityId");
        query.setParameter("utilityId", utilityId);

        List<?> keys = query.getResultList();
        for (Object key : keys) {
            result.add(UUID.fromString((String) key));
        }

        return result;
    }

    /**
     * Get the unique user keys for a given utility id.
     *
     * @param utilityId the utility id.
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility(int utilityId) {
        ArrayList<UUID> result = new ArrayList<UUID>();

        Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from utility u "
                        + "inner join account a on u.id = a.utility_id where u.id = :utilityId");
        query.setParameter("utilityId", utilityId);

        List<?> keys = query.getResultList();
        for (Object key : keys) {
            result.add(UUID.fromString((String) key));
        }

        return result;
    }

Replace Generic With Diamond ArrayList<UUID> with ArrayList<> in method public getUserKeysForUtility(utilityId int) : List<UUID> from class eu.daiad.web.repository.application.JpaUserRepository


    /**
     * Get the unique user keys for the default utility of the currently authenticated user.
     *
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility() {
        ArrayList<UUID> result = new ArrayList<>();

        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            AuthenticatedUser user = null;

            if (auth.getPrincipal() instanceof AuthenticatedUser) {
                user = (AuthenticatedUser) auth.getPrincipal();
            }

            if (user != null) {
                Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from account a where a.utility_id = :utility_id");
                query.setParameter("utility_id", user.getUtilityId());

                List<?> keys = query.getResultList();

                // Force device loading
                for (Object key : keys) {
                    result.add(UUID.fromString((String) key));
                }
            }
        } catch (Exception ex) {
            logger.error("Failed to load user keys for utility.", ex);
        }

        return result;
    }

    /**
     * Get the unique user keys for the default utility of the currently authenticated user.
     *
     * @return a list of user keys.
     */
    @Override
    public List<UUID> getUserKeysForUtility() {
        ArrayList<UUID> result = new ArrayList<UUID>();

        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            AuthenticatedUser user = null;

            if (auth.getPrincipal() instanceof AuthenticatedUser) {
                user = (AuthenticatedUser) auth.getPrincipal();
            }

            if (user != null) {
                Query query = entityManager.createNativeQuery("select CAST(a.key as char varying) from account a where a.utility_id = :utility_id");
                query.setParameter("utility_id", user.getUtilityId());

                List<?> keys = query.getResultList();

                // Force device loading
                for (Object key : keys) {
                    result.add(UUID.fromString((String) key));
                }
            }
        } catch (Exception ex) {
            logger.error("Failed to load user keys for utility.", ex);
        }

        return result;
    }

Replace Generic With Diamond ArrayList<UUID> with ArrayList<> in method public getUserKeysForUtility() : List<UUID> from class eu.daiad.web.repository.application.JpaUserRepository


    @Override
    public void setProfileModes(ProfileModesSubmitChangesRequest modeChangesObject) throws ApplicationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        AuthenticatedUser user = null;

        if (auth.getPrincipal() instanceof AuthenticatedUser) {
            user = (AuthenticatedUser) auth.getPrincipal();
        } else {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION_ANONYMOUS_SESSION);
        }

        if (!user.hasRole(EnumRole.ROLE_UTILITY_ADMIN, EnumRole.ROLE_SYSTEM_ADMIN)) {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION);
        }

        List<DeviceAmphiroDefaultConfigurationEntity> configurations = deviceRepository
                        .getAmphiroDefaultConfigurations();

        // Organizing amphiro default configurations in a handy HashMap
        HashMap<String, DeviceAmphiroDefaultConfigurationEntity> defaultconfigurations = new HashMap<>();
        for (DeviceAmphiroDefaultConfigurationEntity defconf : configurations) {
            if (defconf.getTitle().equals("Enabled Configuration (Metric Units)")) {
                defaultconfigurations.put("ON_Metric", defconf);
            } else if (defconf.getTitle().equals("Enabled Configuration (Imperial Units)")) {
                defaultconfigurations.put("ON_Imperial", defconf);
            } else {
                defaultconfigurations.put("OFF", defconf);
            }
        }

        for (ProfileModesChanges modeChanges : modeChangesObject.getModeChanges()) {

            String accountQueryString = "select a from account a where a.key = :key";
            TypedQuery<AccountEntity> accountQuery = entityManager.createQuery(accountQueryString, AccountEntity.class)
                                                                  .setFirstResult(0).setMaxResults(1);
            accountQuery.setParameter("key", modeChanges.getId());

            AccountEntity account = accountQuery.getSingleResult();

            for (ProfileModeChange modeChange : modeChanges.getChanges()) {
                switch (modeChange.getMode()) {
                    case "amphiro":
                        // Selecting the suitable default configuration
                        DeviceAmphiroDefaultConfigurationEntity newDefaultConfiguration = null;
                        if (modeChange.getValue().equals("OFF")) {
                            newDefaultConfiguration = defaultconfigurations.get("OFF");
                        } else if (modeChange.getValue().equals("ON")) {
                            if (account.getUtility().getName().equals("St Albans")) {
                                newDefaultConfiguration = defaultconfigurations.get("ON_Imperial");
                            } else if (account.getUtility().getName().equals("Alicante")) {
                                newDefaultConfiguration = defaultconfigurations.get("ON_Metric");
                            } else {
                                if (account.getLocale().equals("en")) {
                                    newDefaultConfiguration = defaultconfigurations.get("ON_Imperial");
                                } else {
                                    newDefaultConfiguration = defaultconfigurations.get("ON_Metric");
                                }
                            }

                            // Set also mobile mode to OFF, if the user
                            // hasn't set explicitly mobile mode
                            boolean mobileModeChangeExists = false;
                            for (ProfileModeChange change : modeChanges.getChanges()) {
                                if (change.getMode().equals("mobile")) {
                                    mobileModeChangeExists = true;
                                }
                            }
                            if (!mobileModeChangeExists) {
                                setMobileMode(account, EnumMobileMode.INACTIVE.getValue());
                            }
                        } else {
                            newDefaultConfiguration = defaultconfigurations.get("OFF");
                        }

                        // Get the current (active and inactive)
                        // configurations and set them as inactive
                        Set<eu.daiad.web.domain.application.DeviceEntity> devices = account.getDevices();
                        for (eu.daiad.web.domain.application.DeviceEntity device : devices) {

                            if (device.getType() == EnumDeviceType.AMPHIRO) {
                                DeviceAmphiroConfigurationEntity newConfiguration = new DeviceAmphiroConfigurationEntity();

                                newConfiguration.setActive(true);
                                newConfiguration.setCreatedOn(new DateTime());
                                newConfiguration.setTitle(newDefaultConfiguration.getTitle());
                                newConfiguration.setBlock(newDefaultConfiguration.getBlock());
                                newConfiguration.setValue1(newDefaultConfiguration.getValue1());
                                newConfiguration.setValue2(newDefaultConfiguration.getValue2());
                                newConfiguration.setValue3(newDefaultConfiguration.getValue3());
                                newConfiguration.setValue4(newDefaultConfiguration.getValue4());
                                newConfiguration.setValue5(newDefaultConfiguration.getValue5());
                                newConfiguration.setValue6(newDefaultConfiguration.getValue6());
                                newConfiguration.setValue7(newDefaultConfiguration.getValue7());
                                newConfiguration.setValue8(newDefaultConfiguration.getValue8());
                                newConfiguration.setValue9(newDefaultConfiguration.getValue9());
                                newConfiguration.setValue10(newDefaultConfiguration.getValue10());
                                newConfiguration.setValue11(newDefaultConfiguration.getValue11());
                                newConfiguration.setValue12(newDefaultConfiguration.getValue12());
                                newConfiguration.setNumberOfFrames(newDefaultConfiguration.getNumberOfFrames());
                                newConfiguration.setFrameDuration(newDefaultConfiguration.getFrameDuration());

                                DeviceAmphiroEntity deviceAmphiro = (DeviceAmphiroEntity) device;
                                for (DeviceAmphiroConfigurationEntity currentConfiguration : deviceAmphiro
                                                .getConfigurations()) {
                                    currentConfiguration.setActive(false);
                                }
                                deviceAmphiro.getConfigurations().add(newConfiguration);
                            }
                        }

                        break;
                    case "mobile":
                        int newMobileMode = EnumMobileMode.UNDEFINED.getValue();
                        if (modeChange.getValue().equals("ON")) {
                            newMobileMode = EnumMobileMode.ACTIVE.getValue();
                        } else if (modeChange.getValue().equals("OFF")) {
                            newMobileMode = EnumMobileMode.INACTIVE.getValue();
                        }
                        setMobileMode(account, newMobileMode);

                        break;
                    case "web":
                        int newWebMode = EnumWebMode.UNDEFINED.getValue();
                        if (modeChange.getValue().equals("ON")) {
                            newWebMode = EnumWebMode.ACTIVE.getValue();
                        } else if (modeChange.getValue().equals("OFF")) {
                            newWebMode = EnumWebMode.INACTIVE.getValue();
                        }
                        setWebMode(account, newWebMode);

                        break;
                    case "social":
                        boolean isSocialEnabled = false;
                        if (modeChange.getValue().equals("ON")) {
                            isSocialEnabled = true;
                        } else if (modeChange.getValue().equals("OFF")) {
                            isSocialEnabled = false;
                        }
                        setSocial(account, isSocialEnabled);

                        break;
                }

                entityManager.persist(account);
            }
        }
    }

    @Override
    public void setProfileModes(ProfileModesSubmitChangesRequest modeChangesObject) throws ApplicationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        AuthenticatedUser user = null;

        if (auth.getPrincipal() instanceof AuthenticatedUser) {
            user = (AuthenticatedUser) auth.getPrincipal();
        } else {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION_ANONYMOUS_SESSION);
        }

        if (!user.hasRole(EnumRole.ROLE_UTILITY_ADMIN, EnumRole.ROLE_SYSTEM_ADMIN)) {
            throw createApplicationException(SharedErrorCode.AUTHORIZATION);
        }

        List<DeviceAmphiroDefaultConfigurationEntity> configurations = deviceRepository
                        .getAmphiroDefaultConfigurations();

        // Organizing amphiro default configurations in a handy HashMap
        HashMap<String, DeviceAmphiroDefaultConfigurationEntity> defaultconfigurations = new HashMap<String, DeviceAmphiroDefaultConfigurationEntity>();
        for (DeviceAmphiroDefaultConfigurationEntity defconf : configurations) {
            if (defconf.getTitle().equals("Enabled Configuration (Metric Units)")) {
                defaultconfigurations.put("ON_Metric", defconf);
            } else if (defconf.getTitle().equals("Enabled Configuration (Imperial Units)")) {
                defaultconfigurations.put("ON_Imperial", defconf);
            } else {
                defaultconfigurations.put("OFF", defconf);
            }
        }

        for (ProfileModesChanges modeChanges : modeChangesObject.getModeChanges()) {

            String accountQueryString = "select a from account a where a.key = :key";
            TypedQuery<AccountEntity> accountQuery = entityManager.createQuery(accountQueryString, AccountEntity.class)
                                                                  .setFirstResult(0).setMaxResults(1);
            accountQuery.setParameter("key", modeChanges.getId());

            AccountEntity account = accountQuery.getSingleResult();

            for (ProfileModeChange modeChange : modeChanges.getChanges()) {
                switch (modeChange.getMode()) {
                    case "amphiro":
                        // Selecting the suitable default configuration
                        DeviceAmphiroDefaultConfigurationEntity newDefaultConfiguration = null;
                        if (modeChange.getValue().equals("OFF")) {
                            newDefaultConfiguration = defaultconfigurations.get("OFF");
                        } else if (modeChange.getValue().equals("ON")) {
                            if (account.getUtility().getName().equals("St Albans")) {
                                newDefaultConfiguration = defaultconfigurations.get("ON_Imperial");
                            } else if (account.getUtility().getName().equals("Alicante")) {
                                newDefaultConfiguration = defaultconfigurations.get("ON_Metric");
                            } else {
                                if (account.getLocale().equals("en")) {
                                    newDefaultConfiguration = defaultconfigurations.get("ON_Imperial");
                                } else {
                                    newDefaultConfiguration = defaultconfigurations.get("ON_Metric");
                                }
                            }

                            // Set also mobile mode to OFF, if the user
                            // hasn't set explicitly mobile mode
                            boolean mobileModeChangeExists = false;
                            for (ProfileModeChange change : modeChanges.getChanges()) {
                                if (change.getMode().equals("mobile")) {
                                    mobileModeChangeExists = true;
                                }
                            }
                            if (!mobileModeChangeExists) {
                                setMobileMode(account, EnumMobileMode.INACTIVE.getValue());
                            }
                        } else {
                            newDefaultConfiguration = defaultconfigurations.get("OFF");
                        }

                        // Get the current (active and inactive)
                        // configurations and set them as inactive
                        Set<eu.daiad.web.domain.application.DeviceEntity> devices = account.getDevices();
                        for (eu.daiad.web.domain.application.DeviceEntity device : devices) {

                            if (device.getType() == EnumDeviceType.AMPHIRO) {
                                DeviceAmphiroConfigurationEntity newConfiguration = new DeviceAmphiroConfigurationEntity();

                                newConfiguration.setActive(true);
                                newConfiguration.setCreatedOn(new DateTime());
                                newConfiguration.setTitle(newDefaultConfiguration.getTitle());
                                newConfiguration.setBlock(newDefaultConfiguration.getBlock());
                                newConfiguration.setValue1(newDefaultConfiguration.getValue1());
                                newConfiguration.setValue2(newDefaultConfiguration.getValue2());
                                newConfiguration.setValue3(newDefaultConfiguration.getValue3());
                                newConfiguration.setValue4(newDefaultConfiguration.getValue4());
                                newConfiguration.setValue5(newDefaultConfiguration.getValue5());
                                newConfiguration.setValue6(newDefaultConfiguration.getValue6());
                                newConfiguration.setValue7(newDefaultConfiguration.getValue7());
                                newConfiguration.setValue8(newDefaultConfiguration.getValue8());
                                newConfiguration.setValue9(newDefaultConfiguration.getValue9());
                                newConfiguration.setValue10(newDefaultConfiguration.getValue10());
                                newConfiguration.setValue11(newDefaultConfiguration.getValue11());
                                newConfiguration.setValue12(newDefaultConfiguration.getValue12());
                                newConfiguration.setNumberOfFrames(newDefaultConfiguration.getNumberOfFrames());
                                newConfiguration.setFrameDuration(newDefaultConfiguration.getFrameDuration());

                                DeviceAmphiroEntity deviceAmphiro = (DeviceAmphiroEntity) device;
                                for (DeviceAmphiroConfigurationEntity currentConfiguration : deviceAmphiro
                                                .getConfigurations()) {
                                    currentConfiguration.setActive(false);
                                }
                                deviceAmphiro.getConfigurations().add(newConfiguration);
                            }
                        }

                        break;
                    case "mobile":
                        int newMobileMode = EnumMobileMode.UNDEFINED.getValue();
                        if (modeChange.getValue().equals("ON")) {
                            newMobileMode = EnumMobileMode.ACTIVE.getValue();
                        } else if (modeChange.getValue().equals("OFF")) {
                            newMobileMode = EnumMobileMode.INACTIVE.getValue();
                        }
                        setMobileMode(account, newMobileMode);

                        break;
                    case "web":
                        int newWebMode = EnumWebMode.UNDEFINED.getValue();
                        if (modeChange.getValue().equals("ON")) {
                            newWebMode = EnumWebMode.ACTIVE.getValue();
                        } else if (modeChange.getValue().equals("OFF")) {
                            newWebMode = EnumWebMode.INACTIVE.getValue();
                        }
                        setWebMode(account, newWebMode);

                        break;
                    case "social":
                        boolean isSocialEnabled = false;
                        if (modeChange.getValue().equals("ON")) {
                            isSocialEnabled = true;
                        } else if (modeChange.getValue().equals("OFF")) {
                            isSocialEnabled = false;
                        }
                        setSocial(account, isSocialEnabled);

                        break;
                }

                entityManager.persist(account);
            }
        }
    }

Replace Generic With Diamond HashMap<String,DeviceAmphiroDefaultConfigurationEntity> with HashMap<> in method public setProfileModes(modeChangesObject ProfileModesSubmitChangesRequest) : void from class eu.daiad.web.repository.application.JpaProfileRepository


    @Override
    public List<ProfileHistoryEntry> getProfileHistoryByUserKey(UUID userKey) {
        String sqlString = "select a from account a where a.key = :userKey";

        TypedQuery<AccountEntity> query = entityManager.createQuery(sqlString, AccountEntity.class)
                                                       .setFirstResult(0)
                                                       .setMaxResults(1);
        query.setParameter("userKey", userKey);

        AccountEntity account = query.getSingleResult();

        List<ProfileHistoryEntry> entries = new ArrayList<>();

        for (AccountProfileHistoryEntity h : account.getProfile().getHistory()) {
            ProfileHistoryEntry entry = new ProfileHistoryEntry();

            entry.setAcknowledgedOn(h.getAcknowledgedOn());
            entry.setEnabledOn(h.getEnabledOn());
            entry.setId(h.getId());
            entry.setMobileMode(EnumMobileMode.fromInteger(h.getMobileMode()));
            entry.setWebMode(EnumWebMode.fromInteger(h.getWebMode()));
            entry.setUtilityMode(EnumUtilityMode.fromInteger(h.getUtilityMode()));
            entry.setSocialEnabled(h.isSocialEnabled());
            entry.setUpdatedOn(h.getUpdatedOn());
            entry.setVersion(h.getVersion());

            entries.add(entry);
        }

        Collections.sort(entries, new Comparator<ProfileHistoryEntry>() {

            @Override
            public int compare(ProfileHistoryEntry e1, ProfileHistoryEntry e2) {
                if (e1.getUpdatedOn().getMillis() == e2.getUpdatedOn().getMillis()) {
                    throw new RuntimeException("History entry updated timestamp must be unique.");
                } else if (e1.getUpdatedOn().getMillis() < e2.getUpdatedOn().getMillis()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        return entries;
    }

    @Override
    public List<ProfileHistoryEntry> getProfileHistoryByUserKey(UUID userKey) {
        String sqlString = "select a from account a where a.key = :userKey";

        TypedQuery<AccountEntity> query = entityManager.createQuery(sqlString, AccountEntity.class)
                                                       .setFirstResult(0)
                                                       .setMaxResults(1);
        query.setParameter("userKey", userKey);

        AccountEntity account = query.getSingleResult();

        List<ProfileHistoryEntry> entries = new ArrayList<ProfileHistoryEntry>();

        for (AccountProfileHistoryEntity h : account.getProfile().getHistory()) {
            ProfileHistoryEntry entry = new ProfileHistoryEntry();

            entry.setAcknowledgedOn(h.getAcknowledgedOn());
            entry.setEnabledOn(h.getEnabledOn());
            entry.setId(h.getId());
            entry.setMobileMode(EnumMobileMode.fromInteger(h.getMobileMode()));
            entry.setWebMode(EnumWebMode.fromInteger(h.getWebMode()));
            entry.setUtilityMode(EnumUtilityMode.fromInteger(h.getUtilityMode()));
            entry.setSocialEnabled(h.isSocialEnabled());
            entry.setUpdatedOn(h.getUpdatedOn());
            entry.setVersion(h.getVersion());

            entries.add(entry);
        }

        Collections.sort(entries, new Comparator<ProfileHistoryEntry>() {

            @Override
            public int compare(ProfileHistoryEntry e1, ProfileHistoryEntry e2) {
                if (e1.getUpdatedOn().getMillis() == e2.getUpdatedOn().getMillis()) {
                    throw new RuntimeException("History entry updated timestamp must be unique.");
                } else if (e1.getUpdatedOn().getMillis() < e2.getUpdatedOn().getMillis()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        return entries;
    }

Replace Generic With Diamond ArrayList<ProfileHistoryEntry> with ArrayList<> in method public getProfileHistoryByUserKey(userKey UUID) : List<ProfileHistoryEntry> from class eu.daiad.web.repository.application.JpaProfileRepository


    @Override
    protected void setUp_custom() {
        this.quest = (QuestBuilder) this.director.getCurrentInstance(QuestBuilder.class);

        this.npcList = new ArrayList<>(this.quest.getQuestNPCs().values());
    }

    @Override
    protected void setUp_custom() {
        this.quest = (QuestBuilder) this.director.getCurrentInstance(QuestBuilder.class);

        this.npcList = new ArrayList<QuestNPC>(this.quest.getQuestNPCs().values());
    }

Replace Generic With Diamond ArrayList<QuestNPC> with ArrayList<> in method protected setUp_custom() : void from class playerquests.builder.gui.dynamic.Dynamicselectnpc


    public synchronized Database init() {
        String dbVersion = getPluginVersion();
        String version = "0.0"; // default version

        try (InputStream inputStream = getClass().getResourceAsStream("/META-INF/maven/moe.sammypanda/playerquests/pom.xml")) {
            if (inputStream != null) {
                MavenXpp3Reader reader = new MavenXpp3Reader();
                Model model = reader.read(new InputStreamReader(inputStream));
                version = model.getVersion();
            } else {
                System.err.println("Error: Resource not found.");
            }
        } catch (IOException | XmlPullParserException e) {
            System.err.println("Error reading pom.xml: " + e.getMessage());
        }

        try (Connection connection = getConnection();
            Statement statement = connection.createStatement()) {

            String pluginTableSQL = "CREATE TABLE IF NOT EXISTS plugin ("
            + "plugin TEXT PRIMARY KEY,"
            + "version TEXT NOT NULL,"
            + "CONSTRAINT single_row_constraint UNIQUE (plugin));";
            statement.execute(pluginTableSQL);

            String playersTableSQL = "CREATE TABLE IF NOT EXISTS players ("
            + "uuid TEXT PRIMARY KEY NOT NULL);";
            statement.execute(playersTableSQL);

            String questsTableSQL = "CREATE TABLE IF NOT EXISTS quests ("
            + "id TEXT PRIMARY KEY,"
            + "toggled BOOLEAN NOT NULL DEFAULT TRUE);";
            statement.execute(questsTableSQL);

            String diariesTableSQL = "CREATE TABLE IF NOT EXISTS diaries ("
            + "id TEXT PRIMARY KEY NOT NULL,"
            + "player TEXT UNIQUE,"
            + "FOREIGN KEY (player) REFERENCES players(uuid));";
            statement.execute(diariesTableSQL);

            String diary_questsTableSQL = "CREATE TABLE IF NOT EXISTS diary_quests ("
            + "id TEXT PRIMARY KEY,"
            + "stage TEXT NOT NULL,"
            + "action TEXT,"
            + "quest TEXT,"
            + "diary TEXT,"
            + "FOREIGN KEY (quest) REFERENCES quests(id)"
            + "FOREIGN KEY (diary) REFERENCES diaries(id));";
            statement.execute(diary_questsTableSQL);

            migrate(version, dbVersion);

        } catch (SQLException e) {
            System.err.println("Could not initialise the database: " + e.getMessage());
        }

        return this;
    }

    /**
     * Creates tables if they do not already exist.
     */
    public Database init() {
        String version = "0.0";
        String version_db = Database.getPluginVersion();

        try (InputStream inputStream = getClass().getResourceAsStream("/META-INF/maven/moe.sammypanda/playerquests/pom.xml")) {
            if (inputStream != null) {
                MavenXpp3Reader reader = new MavenXpp3Reader();
                Model model = reader.read(new InputStreamReader(inputStream));

                // get the actual version from the POM
                version = model.getVersion();
            } else {
                System.err.println("Error: Resource not found.");
            }
        } catch (IOException | XmlPullParserException e) {
            System.err.println("Error reading pom.xml: " + e.getMessage());
        }

        try {
            Statement statement = getConnection().createStatement();

            // Create plugin table (for storing info)
            String pluginTableSQL = "CREATE TABLE IF NOT EXISTS plugin ("
            + "plugin TEXT PRIMARY KEY,"
            + "version TEXT NOT NULL,"
            + "CONSTRAINT single_row_constraint UNIQUE (plugin));";
            statement.execute(pluginTableSQL);

            // Create players table
            String playersTableSQL = "CREATE TABLE IF NOT EXISTS players ("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "uuid TEXT NOT NULL);";
            statement.execute(playersTableSQL);

            // Create quests table
            String questsTableSQL = "CREATE TABLE IF NOT EXISTS quests ("
                + "id TEXT PRIMARY KEY,"
                + "toggled BOOLEAN NOT NULL DEFAULT TRUE);";
            statement.execute(questsTableSQL);

            // Create diaries table
            String diariesTableSQL = "CREATE TABLE IF NOT EXISTS diaries ("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "player INTEGER UNIQUE,"
                + "FOREIGN KEY (player) REFERENCES players(id));";
            statement.execute(diariesTableSQL);

            // Create diary_quests table
            String diary_questsTableSQL = "CREATE TABLE IF NOT EXISTS diary_quests ("
                + "id TEXT PRIMARY KEY,"
                + "stage TEXT NOT NULL,"
                + "action TEXT,"
                + "quest TEXT,"
                + "diary INTEGER,"
                + "FOREIGN KEY (quest) REFERENCES quests(id)"
                + "FOREIGN KEY (diary) REFERENCES diaries(id));";
            statement.execute(diary_questsTableSQL);

            statement.close();
            getConnection().close();

            Database.migrate(version, version_db);

        } catch (SQLException e) {
            System.err.println("Could not initialise the database: " + e.getMessage());
        }

        return this;
    }

Try With Resources try(Connection connection=getConnection(); Statement statement=connection.createStatement()) in method public init() : Database from class playerquests.utility.singleton.Database


    public synchronized String getPluginVersion() {
        if (!Files.exists(Paths.get("plugins/PlayerQuests/playerquests.db"))) {
            return "0.0";
        }

        try (Connection connection = getConnection();
            PreparedStatement statement = connection.prepareStatement("SELECT version FROM plugin WHERE plugin = 'PlayerQuests';")) {

            ResultSet results = statement.executeQuery();
            String version = results.getString("version");

            return version;
        } catch (SQLException e) {
            System.err.println("Could not find the quest version in the db " + e.getMessage());
            return "0.0";
        }
    }

    public static String getPluginVersion() {
        if (!Files.exists(Paths.get("plugins/PlayerQuests/playerquests.db"))) {
            // Don't try to continue with fetching version if no database
            return "0.0";
        }

        try {
            Statement statement = getConnection().createStatement();

            // Get PlayerQuests version from plugin table
            String getVersionSQL = "SELECT version FROM plugin WHERE plugin = 'PlayerQuests';";
            ResultSet results = statement.executeQuery(getVersionSQL);
            String version = results.getString("version");

            getConnection().close();
            return version;

        } catch (SQLException e) {
            System.err.println("Could not find the quest version in the db " + e.getMessage());
            return "0.0";
        }
    }

Try With Resources try(Connection connection=getConnection(); PreparedStatement statement=connection.prepareStatement("SELECT version FROM plugin WHERE plugin = 'PlayerQuests';")) in method public getPluginVersion() : String from class playerquests.utility.singleton.Database


    private synchronized void setPluginVersion(String version) {
        try (Connection connection = getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("""
                INSERT INTO plugin (plugin, version)
                VALUES ('PlayerQuests', ?)
                ON CONFLICT(plugin)
                DO UPDATE SET version = excluded.version;
            """)) {

            preparedStatement.setString(1, version);

            preparedStatement.execute();

        } catch (SQLException e) {
            System.err.println("Could not insert or set the quest version in the db " + e.getMessage());
        }
    }

    private static void setPluginVersion(String version) {
        try {
            // Set PlayerQuests version in plugin table
            String setVersionSQL = "UPDATE plugin SET version = ? WHERE plugin = 'PlayerQuests';";
            PreparedStatement preparedStatement = getConnection().prepareStatement(setVersionSQL);
            preparedStatement.setString(1, version);
            preparedStatement.execute();

            getConnection().close();

        } catch (SQLException e) {
            System.err.println("Could not set the quest version in the db " + e.getMessage());
        }
    }

Try With Resources try(Connection connection=getConnection(); PreparedStatement preparedStatement=connection.prepareStatement("""
                INSERT INTO plugin (plugin, version)
                VALUES ('PlayerQuests', ?)
                ON CONFLICT(plugin)
                DO UPDATE SET version = excluded.version;
            """)) in method private setPluginVersion(version String) : void from class playerquests.utility.singleton.Database


    public synchronized List<String> getAllQuests() {
        List<String> ids = new ArrayList<>();
        try (Connection connection = getConnection();
        Statement statement = connection.createStatement()) {

            String allQuestsSQL = "SELECT id FROM quests;";
            ResultSet result = statement.executeQuery(allQuestsSQL);

            while (result.next()) {
                ids.add(result.getString("id"));
            }

        } catch (SQLException e) {
            System.err.println("Could not retrieve quests from database. " + e.getMessage());
        }
        return ids;
    }

    /**
     * Gets the id for all quests, as stored in the database.
     * @return all known quest IDs
     */
    public List<String> getAllQuests() {
        // Create list to add results to
        List<String> ids = new ArrayList<String>();

        // Get quest IDs from quests table
        try {
            Statement statement = getConnection().createStatement();
            String allQuestsSQL = "SELECT id FROM quests;";

            ResultSet result = statement.executeQuery(allQuestsSQL);

            while(result.next()) {
                ids.add(result.getString("id"));
            }

            return ids;

        } catch (SQLException e) {
            System.err.println("Could not retrieve quests from database. " + e.getMessage());
            return null;
        }
    }

Try With Resources try(Connection connection=getConnection(); Statement statement=connection.createStatement()) in method public getAllQuests() : List<String> from class playerquests.utility.singleton.Database


    public synchronized String getQuest(String id) {
        if (id == null) {
            return null;
        }

        try (Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT id FROM quests WHERE id = ?;")) {

            preparedStatement.setString(1, id);

            ResultSet results = preparedStatement.executeQuery();
            String quest = results.getString("id");

            return quest;
        } catch (SQLException e) {
            System.err.println("Could not get the quest " + id + ". " + e.getMessage());
            return null;
        }
    }

    /**
     * Adds a quest reference to the database.
     * @param id the ID to refer to the quest by
     */
    public static String getQuest(String id) {
        if (id == null) {
            return null;
        }

        try {
            // Add player to players table
            String addQuestSQL = "SELECT id FROM quests WHERE id = ?;";

            PreparedStatement preparedStatement = getConnection().prepareStatement(addQuestSQL);

            preparedStatement.setString(1, id); // parameterIndex starts at 1

            ResultSet results = preparedStatement.executeQuery();
            String quest = results.getString("id");

            getConnection().close();

            return quest;

        } catch (SQLException e) {
            System.err.println("Could not get the quest " + id + ". " + e.getMessage());
            return null;
        }
    }

Try With Resources try(Connection connection=getConnection(); PreparedStatement preparedStatement=connection.prepareStatement("SELECT id FROM quests WHERE id = ?;")) in method public getQuest(id String) : String from class playerquests.utility.singleton.Database