
org.jsoftware.restclient.plugins.BaseURLPlugin Maven / Gradle / Ivy
The newest version!
package org.jsoftware.restclient.plugins;
import org.jetbrains.annotations.NotNull;
import org.jsoftware.restclient.RestClientPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URL;
/**
* If request's url doesn't start with http://
or https://
then add baseURL as URL prefix.
*
* Example:
* if baseURL equals "http://somewhere.com/api"
* than restClient.get("users")
will be rewrite to "http://somewhere.com/api/method".
* Plugins are ordered as it was added so remember to put this plugin at the begging.
*
* @author szalik
*/
public class BaseURLPlugin implements RestClientPlugin {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final String baseURL;
/**
* @param baseURL BaseURL
* @throws IllegalArgumentException if baseURL is not valid URL
*/
public BaseURLPlugin(@NotNull String baseURL) throws IllegalArgumentException {
try {
new URL(baseURL);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Argument is not valid URL - '" + baseURL + "'", e);
}
this.baseURL = baseURL;
}
@Override
public void plugin(RestClientPlugin.PluginContext context, RestClientPlugin.PluginChain chain) throws Exception {
String current = context.getURI();
String url = current;
String urlLowerCase = current.toLowerCase();
if (! urlLowerCase.startsWith("http://") && ! urlLowerCase.startsWith("https://")) {
url = baseURL + (url.startsWith("/") ? url.substring(1) : url);
}
if (! url.equals(current)) {
logger.debug("URL changed from '{}' to '{}'", current, url);
context.setURI(url);
}
chain.continueChain();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy