Example usage for org.springframework.web.util UriUtils encodeQueryParam

List of usage examples for org.springframework.web.util UriUtils encodeQueryParam

Introduction

In this page you can find the example usage for org.springframework.web.util UriUtils encodeQueryParam.

Prototype

public static String encodeQueryParam(String queryParam, Charset charset) 

Source Link

Document

Encode the given URI query parameter with the given encoding.

Usage

From source file:org.openlmis.fulfillment.service.request.RequestHelper.java

/**
 * Creates a {@link URI} from the given string representation and with the given parameters.
 *//*ww  w.ja v a2 s.c om*/
public static URI createUri(String url, RequestParameters parameters) {
    UriComponentsBuilder builder = UriComponentsBuilder.newInstance().uri(URI.create(url));

    RequestParameters.init().setAll(parameters).forEach(e -> e.getValue().forEach(one -> {
        try {
            builder.queryParam(e.getKey(),
                    UriUtils.encodeQueryParam(String.valueOf(one), StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException ex) {
            throw new EncodingException(ex);
        }
    }));

    return builder.build(true).toUri();
}

From source file:org.slc.sli.dashboard.util.URLBuilder.java

public void addQueryParam(String key, String value) {
    if (url.charAt(url.length() - 1) == '/') {
        url.deleteCharAt(url.length() - 1);
    }/*from ww w  . java 2s  .  c  om*/
    if (url.indexOf("?") < 0) {
        url.append("?");
    } else if (url.charAt(url.length() - 1) != '&') {
        url.append("&");
    }
    url.append(key).append("=");
    try {
        url.append(UriUtils.encodeQueryParam(value, ENCODING));
    } catch (UnsupportedEncodingException e) {
        url.append(value);
    }
}

From source file:com.greglturnquist.spring.social.ecobee.api.impl.ThermostatTemplateTest.java

@Test
public void testGetThermostat() throws Exception {

    final Selection selection = Selection.thermostats("161775386723");
    selection.getSelection().setIncludeRuntime(true);
    selection.getSelection().setIncludeSettings(true);
    selection.getSelection().setIncludeSensors(true);
    final String selectionStr = UriUtils.encodeQueryParam(this.getObjectMapper().writeValueAsString(selection),
            "UTF-8");
    mockServer.expect(requestTo("https://api.ecobee.com/1/thermostat?json=" + selectionStr))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(jsonResource("thermostats"), MediaType.APPLICATION_JSON));

    final Thermostat thermostat = ecobee.thermostatOperations().getThermostat("161775386723");
    assertThat(thermostat, notNullValue());
    assertThat(thermostat.getIdentifier(), equalTo("161775386723"));
    assertThat(thermostat.getName(), equalTo("My Test Thermostat"));
    assertThat(thermostat.getLastModified(), equalTo("2011-01-28 23:40:25"));
    assertThat(thermostat.getSettings().getHvacMode(), equalTo("heat"));
    assertThat(thermostat.getSettings().getVent(), is(nullValue()));
}

From source file:org.mitre.oauth2.service.impl.UriEncodedClientUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException {

    try {/*from  w w  w .ja  v  a2 s  . c  o  m*/
        String decodedClientId = UriUtils.decode(clientId, "UTF-8");

        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(decodedClientId);

        if (client != null) {

            String encodedPassword = UriUtils.encodeQueryParam(Strings.nullToEmpty(client.getClientSecret()),
                    "UTF-8");

            if (config.isHeartMode() || // if we're running HEART mode turn off all client secrets
                    (client.getTokenEndpointAuthMethod() != null
                            && (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)
                                    || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)))) {

                // Issue a random password each time to prevent password auth from being used (or skipped)
                // for private key or shared key clients, see #715

                encodedPassword = new BigInteger(512, new SecureRandom()).toString(16);
            }

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            Collection<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities());
            authorities.add(ROLE_CLIENT);

            return new User(decodedClientId, encodedPassword, enabled, accountNonExpired, credentialsNonExpired,
                    accountNonLocked, authorities);
        } else {
            throw new UsernameNotFoundException("Client not found: " + clientId);
        }
    } catch (UnsupportedEncodingException | InvalidClientException e) {
        throw new UsernameNotFoundException("Client not found: " + clientId);
    }

}

From source file:com.greglturnquist.spring.social.ecobee.api.impl.ThermostatTemplateTest.java

@Test
public void testGetAllThermostats() throws Exception {

    final Selection selection = Selection.allThermostats();
    selection.getSelection().setIncludeRuntime(true);
    selection.getSelection().setIncludeSettings(true);
    selection.getSelection().setIncludeSensors(true);
    final String selectionStr = UriUtils.encodeQueryParam(this.getObjectMapper().writeValueAsString(selection),
            "UTF-8");
    mockServer.expect(requestTo("https://api.ecobee.com/1/thermostat?json=" + selectionStr))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(jsonResource("thermostats"), MediaType.APPLICATION_JSON));

    final List<Thermostat> thermostats = ecobee.thermostatOperations().getAllThermostats();
    assertThat(thermostats.size(), equalTo(1));

    final Thermostat thermostat = thermostats.get(0);
    assertThat(thermostat.getIdentifier(), equalTo("161775386723"));
    assertThat(thermostat.getName(), equalTo("My Test Thermostat"));
    assertThat(thermostat.getLastModified(), equalTo("2011-01-28 23:40:25"));
    assertThat(thermostat.getSettings().getHvacMode(), equalTo("heat"));
    assertThat(thermostat.getSettings().getVent(), is(nullValue()));
}

From source file:technology.tikal.gae.pagination.PaginationModelFactory.java

private static String addUrlParameter(final String url, final String name, final String value) {
    String response = url;/*from w ww.j  av  a  2 s .co  m*/
    if (!StringUtils.isEmpty(value)) {
        if (!StringUtils.contains(response, '?')) {
            response = response + "?";
        } else {
            response = response + "&";
        }
        try {
            response = response + name + "=" + UriUtils.encodeQueryParam(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return response;
}

From source file:com.greglturnquist.spring.social.ecobee.api.impl.ThermostatTemplateTest.java

@Test
public void testGetThermostatSummary() throws Exception {

    final Selection selection = Selection.allThermostats();
    final String selectionStr = UriUtils.encodeQueryParam(this.getObjectMapper().writeValueAsString(selection),
            "UTF-8");
    mockServer.expect(requestTo("https://api.ecobee.com/1/thermostatSummary?json=" + selectionStr))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(jsonResource("thermostatSummary"), MediaType.APPLICATION_JSON));

    final ThermostatSummary thermostatSummary = ecobee.thermostatOperations().getThermostatSummary();
    final List<ThermostatDetails> thermostatDetailsList = thermostatSummary.getParsedRevisionList();

    assertThat(thermostatDetailsList.size(), equalTo(thermostatSummary.getThermostatCount()));

    final ThermostatDetails thermostatDetails1 = thermostatDetailsList.get(0);
    assertThat(thermostatDetails1.getIdentifier(), equalTo("123456789101"));
    assertThat(thermostatDetails1.getName(), equalTo("MyStat"));
    assertThat(thermostatDetails1.isConnected(), equalTo(true));
    assertThat(thermostatDetails1.getThermostatRevision(), equalTo("071223012334"));
    assertThat(thermostatDetails1.getAlertsRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails1.getRuntimeRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails1.getIntervalRevision(), equalTo("080102000000"));

    final ThermostatDetails thermostatDetails2 = thermostatDetailsList.get(1);
    assertThat(thermostatDetails2.getIdentifier(), equalTo("123456789102"));
    assertThat(thermostatDetails2.getName(), equalTo("Room12"));
    assertThat(thermostatDetails2.isConnected(), equalTo(true));
    assertThat(thermostatDetails2.getThermostatRevision(), equalTo("071223012334"));
    assertThat(thermostatDetails2.getAlertsRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails2.getRuntimeRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails2.getIntervalRevision(), equalTo("080102000000"));

    final ThermostatDetails thermostatDetails3 = thermostatDetailsList.get(2);
    assertThat(thermostatDetails3.getIdentifier(), equalTo("123456789103"));
    assertThat(thermostatDetails3.getName(), equalTo(""));
    assertThat(thermostatDetails3.isConnected(), equalTo(false));
    assertThat(thermostatDetails3.getThermostatRevision(), equalTo("071223012334"));
    assertThat(thermostatDetails3.getAlertsRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails3.getRuntimeRevision(), equalTo("080102000000"));
    assertThat(thermostatDetails3.getIntervalRevision(), equalTo("080102000000"));
}

From source file:org.openlmis.fulfillment.service.ObjReferenceExpander.java

/**
 * Expands the DTO object. The requirement is that the field names in the {@code expands}
 * list exactly correspond to the field names in the passed DTO object. Moreover, those fields
 * need to extend the {@link ObjectReferenceDto}. If that's the case, this method will query the
 * URL from {@link ObjectReferenceDto#getHref()} and add the retrieved fields to the
 * representation./*from  www. j a v  a2s.c  o  m*/
 *
 * @param dto the DTO to expand
 * @param expands a set of field names from the passed DTO to expand
 */
public void expandDto(Object dto, Set<String> expands) {
    if (expands == null) {
        return;
    }

    for (String expand : expands) {
        try {
            String[] elements = expand.split("\\.", 2);
            String field = elements[0];

            ObjectReferenceDto refDto = getObjectReferenceDto(dto, field);
            StringBuilder href = new StringBuilder(getHref(expand, refDto));

            if (elements.length >= 2) {
                href.append("?expand=")
                        .append(UriUtils.encodeQueryParam(elements[1], StandardCharsets.UTF_8.name()));
            }

            Class<?> responseType = REF_RESOURCES.computeIfAbsent(field, key -> Map.class);
            Object refObj = retrieve(href.toString(), responseType);
            populate(dto, field, refObj);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            throw new ValidationException(ex, ERROR_DTO_EXPANSION_ASSIGNMENT, expand);
        } catch (UnsupportedEncodingException exp) {
            throw new ValidationException(exp, ERROR_ENCODING);
        }
    }
}

From source file:org.kmnet.com.fw.web.el.Functions.java

/**
 * url encode the given string based on RFC 3986.<br>
 * <p>//w  w  w .ja  v  a 2s. c  o  m
 * url is encoded with "UTF-8".<br>
 * This method is used to encode values in "query" string.
 *
 * In <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>, "query" part in URI is defined as follows:
 * <pre><code>
 *  foo://example.com:8042/over/there?name=ferret#nose
 *  \_/   \______________/\_________/ \_________/ \__/
 *   |           |            |            |        |
 *scheme     authority       path        query   fragment
 * </code></pre>
 *
 *
 *  and, "query" is defined as follows:
 *     <pre><code>
 *query         = *( pchar / "/" / "?" )
 *pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
 *pct-encoded   = "%" HEXDIG HEXDIG
 *     </code></pre>
 *
 * In these characters, as a value of query parameter, <strong>"&", "+" , "=" are percent-encoded</strong>.
 * </p>
 *
 * <h3>sample</h3>
 * <ul>
 *     <li>/ ====&gt; /</li>
 *     <li>? ====&gt; ?</li>
 *     <li>a ====&gt; a</li>
 *     <li>0 ====&gt; 0</li>
 *     <li>- ====&gt; -</li>
 *     <li>. ====&gt; .</li>
 *     <li>_ ====&gt; _</li>
 *     <li>~ ====&gt; ~</li>
 *     <li>! ====&gt; !</li>
 *     <li>$ ====&gt; $</li>
 *     <li>& ====&gt; %26</li>
 *     <li>' ====&gt; '</li>
 *     <li>( ====&gt; (</li>
 *     <li>) ====&gt; )</li>
 *     <li>* ====&gt; *</li>
 *     <li>+ ====&gt; %2B</li>
 *     <li>; ====&gt; ;</li>
 *     <li>= ====&gt; %3D</li>
 *     <li>? ====&gt; %E3%81%82</li>
 * </ul>
 * <p>Characters not listed above are percent-encoded.</p>
 * @param value string to encode
 * @return encoded string based on RFC 3986. returns empty string if <code>value</code> is <code>null</code> or empty.
 * @see <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a> 3.4.Query
 */
public static String u(String value) {
    if (value == null || value.isEmpty()) {
        return "";
    }
    try {
        return UriUtils.encodeQueryParam(value, "UTF-8");
    } catch (UnsupportedEncodingException ignored) {
        // This exception doesn't absolutely occur.
        return value;
    }
}

From source file:de.thm.arsnova.services.UserService.java

public void sendActivationEmail(DbUser dbUser) {
    String activationUrl;/*from  ww w . j a v a 2  s  . com*/
    try {
        activationUrl = MessageFormat.format("{0}{1}/{2}?action=activate&username={3}&key={4}", rootUrl,
                customizationPath, activationPath, UriUtils.encodeQueryParam(dbUser.getUsername(), "UTF-8"),
                dbUser.getActivationKey());
    } catch (UnsupportedEncodingException e1) {
        LOGGER.error(e1.getMessage());

        return;
    }

    sendEmail(dbUser, regMailSubject, MessageFormat.format(regMailBody, activationUrl));
}