Search in sources :

Example 41 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project dhis2-core by dhis2.

the class SimplisticHttpGetGateWay method getRequestEntity.

// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private HttpEntity<String> getRequestEntity(GenericHttpGatewayConfig config, String text, Set<String> recipients) {
    // Matches
    final StringSubstitutor substitutor = new StringSubstitutor(getRequestData(config, text, recipients));
    // on
    // ${...}
    String data = substitutor.replace(config.getConfigurationTemplate());
    return new HttpEntity<>(data, getRequestHeaderParameters(config));
}
Also used : HttpEntity(org.springframework.http.HttpEntity) StringSubstitutor(org.apache.commons.text.StringSubstitutor)

Example 42 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project dhis2-core by dhis2.

the class GenericSmsGatewayTest method testSendSms_Url.

@Test
void testSendSms_Url() {
    username.setHeader(false);
    password.setHeader(false);
    password.setConfidential(true);
    valueStore.put(username.getKey(), username.getValue());
    valueStore.put(password.getKey(), password.getValue());
    strSubstitutor = new StringSubstitutor(valueStore);
    gatewayConfig.getParameters().clear();
    gatewayConfig.setParameters(Arrays.asList(username, password));
    gatewayConfig.setContentType(ContentType.FORM_URL_ENCODED);
    gatewayConfig.setConfigurationTemplate(CONFIG_TEMPLATE_URL_ENCODED);
    body = strSubstitutor.replace(CONFIG_TEMPLATE_URL_ENCODED);
    ResponseEntity<String> responseEntity = new ResponseEntity<>("success", HttpStatus.OK);
    when(pbeStringEncryptor.decrypt(anyString())).thenReturn(password.getValue());
    when(restTemplate.exchange(any(URI.class), any(HttpMethod.class), any(HttpEntity.class), eq(String.class))).thenReturn(responseEntity);
    assertThat(subject.send(SUBJECT, TEXT, RECIPIENTS, gatewayConfig).isOk(), is(true));
    verify(restTemplate).exchange(any(URI.class), httpMethodArgumentCaptor.capture(), httpEntityArgumentCaptor.capture(), eq(String.class));
    assertNotNull(httpEntityArgumentCaptor.getValue());
    assertNotNull(httpMethodArgumentCaptor.getValue());
    HttpMethod httpMethod = httpMethodArgumentCaptor.getValue();
    assertEquals(HttpMethod.POST, httpMethod);
    HttpEntity<String> requestEntity = httpEntityArgumentCaptor.getValue();
    assertEquals(body, requestEntity.getBody());
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) HttpEntity(org.springframework.http.HttpEntity) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.jupiter.api.Test)

Example 43 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project dhis2-core by dhis2.

the class GenericSmsGatewayTest method testSendSms_Json.

@Test
void testSendSms_Json() {
    strSubstitutor = new StringSubstitutor(valueStore);
    body = strSubstitutor.replace(CONFIG_TEMPLATE_JSON);
    gatewayConfig.getParameters().clear();
    gatewayConfig.setParameters(Arrays.asList(username, password));
    gatewayConfig.setContentType(ContentType.APPLICATION_JSON);
    gatewayConfig.setConfigurationTemplate(CONFIG_TEMPLATE_JSON);
    ResponseEntity<String> responseEntity = new ResponseEntity<>("success", HttpStatus.OK);
    when(restTemplate.exchange(any(URI.class), any(HttpMethod.class), any(HttpEntity.class), eq(String.class))).thenReturn(responseEntity);
    assertThat(subject.send(SUBJECT, TEXT, RECIPIENTS, gatewayConfig).isOk(), is(true));
    verify(restTemplate).exchange(any(URI.class), httpMethodArgumentCaptor.capture(), httpEntityArgumentCaptor.capture(), eq(String.class));
    assertNotNull(httpEntityArgumentCaptor.getValue());
    assertNotNull(httpMethodArgumentCaptor.getValue());
    HttpMethod httpMethod = httpMethodArgumentCaptor.getValue();
    assertEquals(HttpMethod.POST, httpMethod);
    HttpEntity<String> requestEntity = httpEntityArgumentCaptor.getValue();
    assertEquals(body, requestEntity.getBody());
    HttpHeaders httpHeaders = requestEntity.getHeaders();
    assertTrue(httpHeaders.get("Content-type").contains(gatewayConfig.getContentType().getValue()));
    List<GenericGatewayParameter> parameters = gatewayConfig.getParameters();
    parameters.stream().filter(p -> p.isEncode() && p.isConfidential() && p.isHeader()).forEach(p -> {
        assertTrue(httpHeaders.containsKey(p.getKey()));
        assertEquals(" Basic ZGVjcnlwdGVkVGV4dA==", httpHeaders.get(p.getKey()).get(0));
    });
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) SmsGateway(org.hisp.dhis.sms.config.SmsGateway) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Mock(org.mockito.Mock) HashMap(java.util.HashMap) GenericGatewayParameter(org.hisp.dhis.sms.config.GenericGatewayParameter) StringUtils(org.apache.commons.lang3.StringUtils) Captor(org.mockito.Captor) StringSubstitutor(org.apache.commons.text.StringSubstitutor) GenericHttpGatewayConfig(org.hisp.dhis.sms.config.GenericHttpGatewayConfig) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) PBEStringEncryptor(org.jasypt.encryption.pbe.PBEStringEncryptor) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) URI(java.net.URI) SmsUtils(org.hisp.dhis.system.util.SmsUtils) RestTemplate(org.springframework.web.client.RestTemplate) SimplisticHttpGetGateWay(org.hisp.dhis.sms.config.SimplisticHttpGetGateWay) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) HttpHeaders(org.springframework.http.HttpHeaders) HttpMethod(org.springframework.http.HttpMethod) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) Sets(com.google.common.collect.Sets) Mockito.verify(org.mockito.Mockito.verify) ContentType(org.hisp.dhis.sms.config.ContentType) Test(org.junit.jupiter.api.Test) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) ResponseEntity(org.springframework.http.ResponseEntity) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpEntity(org.springframework.http.HttpEntity) GenericGatewayParameter(org.hisp.dhis.sms.config.GenericGatewayParameter) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.jupiter.api.Test)

Example 44 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project dhis2-core by dhis2.

the class JdbcCompleteDataSetRegistrationExchangeStore method createQuery.

private static String createQuery(ExportParams params) {
    IdSchemes idSchemes = params.getOutputIdSchemes() != null ? params.getOutputIdSchemes() : new IdSchemes();
    ImmutableMap.Builder<String, String> namedParamsBuilder = ImmutableMap.<String, String>builder().put(DATA_SET_SCHEME, idSchemes.getDataSetIdScheme().getIdentifiableString().toLowerCase()).put(ORG_UNIT_SCHEME, idSchemes.getOrgUnitIdScheme().getIdentifiableString().toLowerCase()).put(ATTR_OPT_COMBO_SCHEME, idSchemes.getAttributeOptionComboIdScheme().getIdentifiableString().toLowerCase());
    String sql = "SELECT ds.${dsScheme} AS dsid, pe.startdate AS pe_start, pt.name AS ptname, ou.${ouScheme} AS ouid, " + "aoc.${aocScheme} AS aocid, cdsr.storedby AS storedby, cdsr.date AS created, cdsr.completed AS completed " + "FROM completedatasetregistration cdsr " + "INNER JOIN dataset ds ON ( cdsr.datasetid=ds.datasetid ) " + "INNER JOIN period pe ON ( cdsr.periodid=pe.periodid ) " + "INNER JOIN periodtype pt ON ( pe.periodtypeid=pt.periodtypeid ) " + "INNER JOIN organisationunit ou ON ( cdsr.sourceid=ou.organisationunitid ) " + "INNER JOIN categoryoptioncombo aoc ON ( cdsr.attributeoptioncomboid = aoc.categoryoptioncomboid ) ";
    sql += createOrgUnitGroupJoin(params);
    sql += createDataSetClause(params, namedParamsBuilder);
    sql += createOrgUnitClause(params, namedParamsBuilder);
    sql += createPeriodClause(params, namedParamsBuilder);
    sql += createCreatedClause(params, namedParamsBuilder);
    sql += createLimitClause(params, namedParamsBuilder);
    sql = new StringSubstitutor(namedParamsBuilder.build(), "${", "}").replace(sql);
    log.debug("CompleteDataSetRegistrations query: " + sql);
    return sql;
}
Also used : IdSchemes(org.hisp.dhis.common.IdSchemes) StringSubstitutor(org.apache.commons.text.StringSubstitutor) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 45 with StringSubstitutor

use of org.apache.commons.text.StringSubstitutor in project dhis2-core by dhis2.

the class AttributeOptionComboLoader method getAttributeOptionCombo.

private CategoryOptionCombo getAttributeOptionCombo(IdScheme idScheme, String categoryComboId, Set<CategoryOption> categoryOptions) {
    final String key = "categorycomboid";
    final String categoryComboKey = resolveId(idScheme, key, categoryComboId);
    final String optionsId = categoryOptions.stream().map(co -> Long.toString(co.getId())).map(s -> "'" + s + "'").collect(Collectors.joining(","));
    StringSubstitutor sub = new StringSubstitutor(ImmutableMap.<String, String>builder().put("resolvedScheme", Objects.requireNonNull(categoryComboKey)).put("option_ids", optionsId).build());
    // TODO use cache
    List<CategoryOptionCombo> categoryOptionCombos = jdbcTemplate.query(sub.replace(SQL_GET_CATEGORYOPTIONCOMBO_BY_CATEGORYIDS), (rs, i) -> bind("categoryoptioncomboid", rs));
    if (categoryOptionCombos.size() == 1) {
        return categoryOptionCombos.get(0);
    } else {
        // TODO throw an error??
        return null;
    }
}
Also used : Arrays(java.util.Arrays) CategoryOption(org.hisp.dhis.category.CategoryOption) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) StringSubstitutor(org.apache.commons.text.StringSubstitutor) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) HashSet(java.util.HashSet) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) IdentifiableProperty(org.hisp.dhis.common.IdentifiableProperty) Qualifier(org.springframework.beans.factory.annotation.Qualifier) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) ImmutableMap(com.google.common.collect.ImmutableMap) ObjectUtils(org.springframework.util.ObjectUtils) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) Sharing(org.hisp.dhis.user.sharing.Sharing) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) JacksonObjectMapperConfig(org.hisp.dhis.commons.jackson.config.JacksonObjectMapperConfig) Component(org.springframework.stereotype.Component) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo) CategoryCombo(org.hisp.dhis.category.CategoryCombo) IdScheme(org.hisp.dhis.common.IdScheme) TextUtils(org.hisp.dhis.commons.util.TextUtils) StringSubstitutor(org.apache.commons.text.StringSubstitutor) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo)

Aggregations

StringSubstitutor (org.apache.commons.text.StringSubstitutor)71 HashMap (java.util.HashMap)24 Test (org.junit.jupiter.api.Test)19 IOException (java.io.IOException)11 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 File (java.io.File)8 List (java.util.List)8 InputStream (java.io.InputStream)6 Collectors (java.util.stream.Collectors)6 StringLookup (org.apache.commons.text.lookup.StringLookup)6 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)6 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)5 SubstitutingSourceProvider (io.dropwizard.configuration.SubstitutingSourceProvider)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 MetricRegistry (com.codahale.metrics.MetricRegistry)4 JsonObject (com.google.gson.JsonObject)4 URL (java.net.URL)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Scanner (java.util.Scanner)4