index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/HystrixObservableCommandChain.java | package com.netflix.ribbon.hystrix;
import com.netflix.hystrix.HystrixObservableCommand;
import rx.Observable;
import rx.functions.Func1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This class implements chaining mechanism for Hystrix commands. If a command in a chain fails, the next one
* is run. If all commands in the chain failed, the error from the last one is reported.
* To be able to identify the Hystrix command for which request was executed, an {@link ResultCommandPair} event
* stream is returned by {@link #toResultCommandPairObservable()} method.
* If information about Hystrix command is not important, {@link #toObservable()} method shall be used, which
* is more efficient.
*
* @author Tomasz Bak
*/
public class HystrixObservableCommandChain<T> {
private final List<HystrixObservableCommand<T>> hystrixCommands;
public HystrixObservableCommandChain(List<HystrixObservableCommand<T>> hystrixCommands) {
this.hystrixCommands = hystrixCommands;
}
public HystrixObservableCommandChain(HystrixObservableCommand<T>... commands) {
hystrixCommands = new ArrayList<HystrixObservableCommand<T>>(commands.length);
Collections.addAll(hystrixCommands, commands);
}
public Observable<ResultCommandPair<T>> toResultCommandPairObservable() {
Observable<ResultCommandPair<T>> rootObservable = null;
for (final HystrixObservableCommand<T> command : hystrixCommands) {
Observable<ResultCommandPair<T>> observable = command.toObservable().map(new Func1<T, ResultCommandPair<T>>() {
@Override
public ResultCommandPair<T> call(T result) {
return new ResultCommandPair<T>(result, command);
}
});
rootObservable = rootObservable == null ? observable : rootObservable.onErrorResumeNext(observable);
}
return rootObservable;
}
public Observable<T> toObservable() {
Observable<T> rootObservable = null;
for (final HystrixObservableCommand<T> command : hystrixCommands) {
Observable<T> observable = command.toObservable();
rootObservable = rootObservable == null ? observable : rootObservable.onErrorResumeNext(observable);
}
return rootObservable;
}
public List<HystrixObservableCommand<T>> getCommands() {
return Collections.unmodifiableList(hystrixCommands);
}
public HystrixObservableCommand getLastCommand() {
return hystrixCommands.get(hystrixCommands.size() - 1);
}
}
| 3,600 |
0 | Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon/src/main/java/com/netflix/ribbon/hystrix/CacheObservableCommand.java | package com.netflix.ribbon.hystrix;
import java.util.Map;
import rx.Observable;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.ribbon.CacheProvider;
/**
* @author Tomasz Bak
*/
public class CacheObservableCommand<T> extends HystrixObservableCommand<T> {
private final CacheProvider<T> cacheProvider;
private final String key;
private final String hystrixCacheKey;
private final Map<String, Object> requestProperties;
public CacheObservableCommand(
CacheProvider<T> cacheProvider,
String key,
String hystrixCacheKey,
Map<String, Object> requestProperties,
Setter setter) {
super(setter);
this.cacheProvider = cacheProvider;
this.key = key;
this.hystrixCacheKey = hystrixCacheKey;
this.requestProperties = requestProperties;
}
@Override
protected String getCacheKey() {
if (hystrixCacheKey == null) {
return super.getCacheKey();
} else {
return hystrixCacheKey;
}
}
@Override
protected Observable<T> construct() {
return cacheProvider.get(key, requestProperties);
}
}
| 3,601 |
0 | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/utils/ScheduledThreadPoolExectuorWithDynamicSize.java | /*
*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.utils;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import com.netflix.config.DynamicIntProperty;
/**
* A {@link ScheduledThreadPoolExecutor} whose core size can be dynamically changed by a given {@link DynamicIntProperty} and
* registers itself with a shutdown hook to shut down.
*
* @author awang
*
* @deprecated This class is no longer necessary as part of Ribbon and should not be used by anyone
*/
@Deprecated
public class ScheduledThreadPoolExectuorWithDynamicSize extends ScheduledThreadPoolExecutor {
private final Thread shutdownThread;
public ScheduledThreadPoolExectuorWithDynamicSize(final DynamicIntProperty corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize.get(), threadFactory);
corePoolSize.addCallback(new Runnable() {
public void run() {
setCorePoolSize(corePoolSize.get());
}
});
shutdownThread = new Thread(new Runnable() {
public void run() {
shutdown();
if (shutdownThread != null) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownThread);
} catch (IllegalStateException ise) { // NOPMD
}
}
}
});
Runtime.getRuntime().addShutdownHook(shutdownThread);
}
}
| 3,602 |
0 | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/SimpleVipAddressResolver.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
/**
* A "VipAddress" in Ribbon terminology is a logical name used for a target
* server farm. This class helps interpret and resolve a "macro" and obtain a
* finalized vipAddress.
* <p>
* Ribbon supports a comma separated set of logcial addresses for a Ribbon
* Client. Typical/default implementation uses the list of servers obtained from
* the first of the comma separated list and progresses down the list only when
* the priorr vipAddress contains no servers.
* <p>
* This class assumes that the vip address string may contain marcos in the format
* of ${foo}, where foo is a property in Archaius configuration, and tries to replace
* these macros with actual values.
*
* <p>
* e.g. vipAddress settings
*
* <code>
* ${foo}.bar:${port},${foobar}:80,localhost:8080
*
* The above list will be resolved by this class as
*
* apple.bar:80,limebar:80,localhost:8080
*
* provided that the Configuration library resolves the property foo=apple,port=80 and foobar=limebar
*
* </code>
*
* @author stonse
*
*/
public class SimpleVipAddressResolver implements VipAddressResolver {
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{(.*?)\\}");
/**
* Resolve the vip address by replacing macros with actual values in configuration.
* If there is no macro, the passed in string will be returned. If a macro is found but
* there is no property defined in configuration, the same macro is returned as part of the
* result.
*/
@Override
public String resolve(String vipAddressMacro, IClientConfig niwsClientConfig) {
if (vipAddressMacro == null || vipAddressMacro.length() == 0) {
return vipAddressMacro;
}
return replaceMacrosFromConfig(vipAddressMacro);
}
private static String replaceMacrosFromConfig(String macro) {
String result = macro;
Matcher matcher = VAR_PATTERN.matcher(result);
while (matcher.find()) {
String key = matcher.group(1);
String value = ConfigurationManager.getConfigInstance().getString(key);
if (value != null) {
result = result.replaceAll("\\$\\{" + key + "\\}", value);
matcher = VAR_PATTERN.matcher(result);
}
}
return result.trim();
}
}
| 3,603 |
0 | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/ArchaiusPropertyResolver.java | package com.netflix.client.config;
import com.netflix.config.ConfigurationManager;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
public class ArchaiusPropertyResolver implements PropertyResolver {
private static final Logger LOG = LoggerFactory.getLogger(ArchaiusPropertyResolver.class);
public static final ArchaiusPropertyResolver INSTANCE = new ArchaiusPropertyResolver();
private final AbstractConfiguration config;
private final CopyOnWriteArrayList<Runnable> actions = new CopyOnWriteArrayList<>();
private ArchaiusPropertyResolver() {
this.config = ConfigurationManager.getConfigInstance();
ConfigurationManager.getConfigInstance().addConfigurationListener(new ConfigurationListener() {
@Override
public void configurationChanged(ConfigurationEvent event) {
if (!event.isBeforeUpdate()) {
actions.forEach(ArchaiusPropertyResolver::invokeAction);
}
}
});
}
private static void invokeAction(Runnable action) {
try {
action.run();
} catch (Exception e) {
LOG.info("Failed to invoke action", e);
}
}
@Override
public <T> Optional<T> get(String key, Class<T> type) {
if (Integer.class.equals(type)) {
return Optional.ofNullable((T) config.getInteger(key, null));
} else if (Boolean.class.equals(type)) {
return Optional.ofNullable((T) config.getBoolean(key, null));
} else if (Float.class.equals(type)) {
return Optional.ofNullable((T) config.getFloat(key, null));
} else if (Long.class.equals(type)) {
return Optional.ofNullable((T) config.getLong(key, null));
} else if (Double.class.equals(type)) {
return Optional.ofNullable((T) config.getDouble(key, null));
} else if (TimeUnit.class.equals(type)) {
return Optional.ofNullable((T) TimeUnit.valueOf(config.getString(key, null)));
} else {
return Optional.ofNullable(config.getStringArray(key))
.filter(ar -> ar.length > 0)
.map(ar -> Arrays.stream(ar).collect(Collectors.joining(",")))
.map(value -> {
if (type.equals(String.class)) {
return (T)value;
} else {
return PropertyUtils.resolveWithValueOf(type, value)
.orElseThrow(() -> new IllegalArgumentException("Unable to convert value to desired type " + type));
}
});
}
}
@Override
public void forEach(String prefix, BiConsumer<String, String> consumer) {
Optional.ofNullable(config.subset(prefix))
.ifPresent(subconfig -> {
subconfig.getKeys().forEachRemaining(key -> {
String value = config.getString(prefix + "." + key);
consumer.accept(key, value);
});
});
}
@Override
public void onChange(Runnable action) {
actions.add(action);
}
public int getActionCount() {
return actions.size();
}
}
| 3,604 |
0 | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/ArchaiusClientConfigFactory.java | package com.netflix.client.config;
public class ArchaiusClientConfigFactory implements ClientConfigFactory {
@Override
public IClientConfig newConfig() {
return new DefaultClientConfigImpl();
}
}
| 3,605 |
0 | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-archaius/src/main/java/com/netflix/client/config/DefaultClientConfigImpl.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client.config;
import java.util.concurrent.TimeUnit;
/**
* Default client configuration that loads properties from Archaius's ConfigurationManager.
* <p>
* The easiest way to configure client and load balancer is through loading properties into Archaius that conform to the specific format:
<pre>{@code
<clientName>.<nameSpace>.<propertyName>=<value>
}</pre>
<p>
You can define properties in a file on classpath or as system properties. If former, ConfigurationManager.loadPropertiesFromResources() API should be called to load the file.
<p>
By default, "ribbon" should be the nameSpace.
<p>
If there is no property specified for a named client, {@code com.netflix.client.ClientFactory} will still create the client and
load balancer with default values for all necessary properties. The default
values are specified in this class as constants.
<p>
If a property is missing the clientName, it is interpreted as a property that applies to all clients. For example
<pre>{@code
ribbon.ReadTimeout=1000
}</pre>
This will establish the default ReadTimeout property for all clients.
<p>
You can also programmatically set properties by constructing instance of DefaultClientConfigImpl. Follow these steps:
<ul>
<li> Get an instance by calling {@link #getClientConfigWithDefaultValues(String)} to load default values,
and any properties that are already defined with Configuration in Archaius
<li> Set all desired properties by calling {@link #setProperty(IClientConfigKey, Object)} API.
<li> Pass this instance together with client name to {@code com.netflix.client.ClientFactory} API.
</ul>
<p><p>
If it is desired to have properties defined in a different name space, for example, "foo"
<pre>{@code
myclient.foo.ReadTimeout=1000
}</pre>
You should use {@link #getClientConfigWithDefaultValues(String, String)} - in the first step above.
*
* @author Sudhir Tonse
* @author awang
*
*/
public class DefaultClientConfigImpl extends AbstractDefaultClientConfigImpl {
public static final String DEFAULT_PROPERTY_NAME_SPACE = CommonClientConfigKey.DEFAULT_NAME_SPACE;
private String propertyNameSpace = DEFAULT_PROPERTY_NAME_SPACE;
@Deprecated
public Boolean getDefaultPrioritizeVipAddressBasedServers() {
return DEFAULT_PRIORITIZE_VIP_ADDRESS_BASED_SERVERS;
}
@Deprecated
public String getDefaultNfloadbalancerPingClassname() {
return DEFAULT_NFLOADBALANCER_PING_CLASSNAME;
}
@Deprecated
public String getDefaultNfloadbalancerRuleClassname() {
return DEFAULT_NFLOADBALANCER_RULE_CLASSNAME;
}
@Deprecated
public String getDefaultNfloadbalancerClassname() {
return DEFAULT_NFLOADBALANCER_CLASSNAME;
}
@Deprecated
public boolean getDefaultUseIpAddressForServer() {
return DEFAULT_USEIPADDRESS_FOR_SERVER;
}
@Deprecated
public String getDefaultClientClassname() {
return DEFAULT_CLIENT_CLASSNAME;
}
@Deprecated
public String getDefaultVipaddressResolverClassname() {
return DEFAULT_VIPADDRESS_RESOLVER_CLASSNAME;
}
@Deprecated
public String getDefaultPrimeConnectionsUri() {
return DEFAULT_PRIME_CONNECTIONS_URI;
}
@Deprecated
public int getDefaultMaxTotalTimeToPrimeConnections() {
return DEFAULT_MAX_TOTAL_TIME_TO_PRIME_CONNECTIONS;
}
@Deprecated
public int getDefaultMaxRetriesPerServerPrimeConnection() {
return DEFAULT_MAX_RETRIES_PER_SERVER_PRIME_CONNECTION;
}
@Deprecated
public Boolean getDefaultEnablePrimeConnections() {
return DEFAULT_ENABLE_PRIME_CONNECTIONS;
}
@Deprecated
public int getDefaultMaxRequestsAllowedPerWindow() {
return DEFAULT_MAX_REQUESTS_ALLOWED_PER_WINDOW;
}
@Deprecated
public int getDefaultRequestThrottlingWindowInMillis() {
return DEFAULT_REQUEST_THROTTLING_WINDOW_IN_MILLIS;
}
@Deprecated
public Boolean getDefaultEnableRequestThrottling() {
return DEFAULT_ENABLE_REQUEST_THROTTLING;
}
@Deprecated
public Boolean getDefaultEnableGzipContentEncodingFilter() {
return DEFAULT_ENABLE_GZIP_CONTENT_ENCODING_FILTER;
}
@Deprecated
public Boolean getDefaultConnectionPoolCleanerTaskEnabled() {
return DEFAULT_CONNECTION_POOL_CLEANER_TASK_ENABLED;
}
@Deprecated
public Boolean getDefaultFollowRedirects() {
return DEFAULT_FOLLOW_REDIRECTS;
}
@Deprecated
public float getDefaultPercentageNiwsEventLogged() {
return DEFAULT_PERCENTAGE_NIWS_EVENT_LOGGED;
}
@Deprecated
public int getDefaultMaxAutoRetriesNextServer() {
return DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER;
}
@Deprecated
public int getDefaultMaxAutoRetries() {
return DEFAULT_MAX_AUTO_RETRIES;
}
@Deprecated
public int getDefaultReadTimeout() {
return DEFAULT_READ_TIMEOUT;
}
@Deprecated
public int getDefaultConnectionManagerTimeout() {
return DEFAULT_CONNECTION_MANAGER_TIMEOUT;
}
@Deprecated
public int getDefaultConnectTimeout() {
return DEFAULT_CONNECT_TIMEOUT;
}
@Deprecated
public int getDefaultMaxHttpConnectionsPerHost() {
return DEFAULT_MAX_HTTP_CONNECTIONS_PER_HOST;
}
@Deprecated
public int getDefaultMaxTotalHttpConnections() {
return DEFAULT_MAX_TOTAL_HTTP_CONNECTIONS;
}
@Deprecated
public int getDefaultMaxConnectionsPerHost() {
return DEFAULT_MAX_CONNECTIONS_PER_HOST;
}
@Deprecated
public int getDefaultMaxTotalConnections() {
return DEFAULT_MAX_TOTAL_CONNECTIONS;
}
@Deprecated
public float getDefaultMinPrimeConnectionsRatio() {
return DEFAULT_MIN_PRIME_CONNECTIONS_RATIO;
}
@Deprecated
public String getDefaultPrimeConnectionsClass() {
return DEFAULT_PRIME_CONNECTIONS_CLASS;
}
@Deprecated
public String getDefaultSeverListClass() {
return DEFAULT_SEVER_LIST_CLASS;
}
@Deprecated
public int getDefaultConnectionIdleTimertaskRepeatInMsecs() {
return DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS;
}
@Deprecated
public int getDefaultConnectionidleTimeInMsecs() {
return DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS;
}
@Deprecated
public int getDefaultPoolMaxThreads() {
return DEFAULT_POOL_MAX_THREADS;
}
@Deprecated
public int getDefaultPoolMinThreads() {
return DEFAULT_POOL_MIN_THREADS;
}
@Deprecated
public long getDefaultPoolKeepAliveTime() {
return DEFAULT_POOL_KEEP_ALIVE_TIME;
}
@Deprecated
public TimeUnit getDefaultPoolKeepAliveTimeUnits() {
return DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS;
}
@Deprecated
public Boolean getDefaultEnableZoneAffinity() {
return DEFAULT_ENABLE_ZONE_AFFINITY;
}
@Deprecated
public Boolean getDefaultEnableZoneExclusivity() {
return DEFAULT_ENABLE_ZONE_EXCLUSIVITY;
}
@Deprecated
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Deprecated
public Boolean getDefaultEnableLoadbalancer() {
return DEFAULT_ENABLE_LOADBALANCER;
}
@Deprecated
public Boolean getDefaultOkToRetryOnAllOperations() {
return DEFAULT_OK_TO_RETRY_ON_ALL_OPERATIONS;
}
@Deprecated
public Boolean getDefaultIsClientAuthRequired(){
return DEFAULT_IS_CLIENT_AUTH_REQUIRED;
}
@Deprecated
public Boolean getDefaultEnableConnectionPool() {
return DEFAULT_ENABLE_CONNECTION_POOL;
}
/**
* Create instance with no properties in default name space {@link #DEFAULT_PROPERTY_NAME_SPACE}
*/
public DefaultClientConfigImpl() {
super(ArchaiusPropertyResolver.INSTANCE);
}
/**
* Create instance with no properties in the specified name space
*/
public DefaultClientConfigImpl(String nameSpace) {
this();
this.propertyNameSpace = nameSpace;
}
public void loadDefaultValues() {
setDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost, getDefaultMaxHttpConnectionsPerHost());
setDefault(CommonClientConfigKey.MaxTotalHttpConnections, getDefaultMaxTotalHttpConnections());
setDefault(CommonClientConfigKey.EnableConnectionPool, getDefaultEnableConnectionPool());
setDefault(CommonClientConfigKey.MaxConnectionsPerHost, getDefaultMaxConnectionsPerHost());
setDefault(CommonClientConfigKey.MaxTotalConnections, getDefaultMaxTotalConnections());
setDefault(CommonClientConfigKey.ConnectTimeout, getDefaultConnectTimeout());
setDefault(CommonClientConfigKey.ConnectionManagerTimeout, getDefaultConnectionManagerTimeout());
setDefault(CommonClientConfigKey.ReadTimeout, getDefaultReadTimeout());
setDefault(CommonClientConfigKey.MaxAutoRetries, getDefaultMaxAutoRetries());
setDefault(CommonClientConfigKey.MaxAutoRetriesNextServer, getDefaultMaxAutoRetriesNextServer());
setDefault(CommonClientConfigKey.OkToRetryOnAllOperations, getDefaultOkToRetryOnAllOperations());
setDefault(CommonClientConfigKey.FollowRedirects, getDefaultFollowRedirects());
setDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, getDefaultConnectionPoolCleanerTaskEnabled());
setDefault(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, getDefaultConnectionidleTimeInMsecs());
setDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval, getDefaultConnectionIdleTimertaskRepeatInMsecs());
setDefault(CommonClientConfigKey.EnableGZIPContentEncodingFilter, getDefaultEnableGzipContentEncodingFilter());
setDefault(CommonClientConfigKey.ProxyHost, null);
setDefault(CommonClientConfigKey.ProxyPort, null);
setDefault(CommonClientConfigKey.Port, getDefaultPort());
setDefault(CommonClientConfigKey.EnablePrimeConnections, getDefaultEnablePrimeConnections());
setDefault(CommonClientConfigKey.MaxRetriesPerServerPrimeConnection, getDefaultMaxRetriesPerServerPrimeConnection());
setDefault(CommonClientConfigKey.MaxTotalTimeToPrimeConnections, getDefaultMaxTotalTimeToPrimeConnections());
setDefault(CommonClientConfigKey.PrimeConnectionsURI, getDefaultPrimeConnectionsUri());
setDefault(CommonClientConfigKey.PoolMinThreads, getDefaultPoolMinThreads());
setDefault(CommonClientConfigKey.PoolMaxThreads, getDefaultPoolMaxThreads());
setDefault(CommonClientConfigKey.PoolKeepAliveTime, (int)getDefaultPoolKeepAliveTime());
setDefault(CommonClientConfigKey.PoolKeepAliveTimeUnits, getDefaultPoolKeepAliveTimeUnits().toString());
setDefault(CommonClientConfigKey.EnableZoneAffinity, getDefaultEnableZoneAffinity());
setDefault(CommonClientConfigKey.EnableZoneExclusivity, getDefaultEnableZoneExclusivity());
setDefault(CommonClientConfigKey.ClientClassName, getDefaultClientClassname());
setDefault(CommonClientConfigKey.NFLoadBalancerClassName, getDefaultNfloadbalancerClassname());
setDefault(CommonClientConfigKey.NFLoadBalancerRuleClassName, getDefaultNfloadbalancerRuleClassname());
setDefault(CommonClientConfigKey.NFLoadBalancerPingClassName, getDefaultNfloadbalancerPingClassname());
setDefault(CommonClientConfigKey.PrioritizeVipAddressBasedServers, getDefaultPrioritizeVipAddressBasedServers());
setDefault(CommonClientConfigKey.MinPrimeConnectionsRatio, getDefaultMinPrimeConnectionsRatio());
setDefault(CommonClientConfigKey.PrimeConnectionsClassName, getDefaultPrimeConnectionsClass());
setDefault(CommonClientConfigKey.NIWSServerListClassName, getDefaultSeverListClass());
setDefault(CommonClientConfigKey.VipAddressResolverClassName, getDefaultVipaddressResolverClassname());
setDefault(CommonClientConfigKey.IsClientAuthRequired, getDefaultIsClientAuthRequired());
setDefault(CommonClientConfigKey.UseIPAddrForServer, getDefaultUseIpAddressForServer());
setDefault(CommonClientConfigKey.ListOfServers, "");
}
@Deprecated
protected void setPropertyInternal(IClientConfigKey propName, Object value) {
set(propName, value);
}
// Helper methods which first check if a "default" (with rest client name)
// property exists. If so, that value is used, else the default value
// passed as argument is used to put into the properties member variable
@Deprecated
protected void putDefaultIntegerProperty(IClientConfigKey propName, Integer defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
protected void putDefaultLongProperty(IClientConfigKey propName, Long defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
protected void putDefaultFloatProperty(IClientConfigKey propName, Float defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
protected void putDefaultTimeUnitProperty(IClientConfigKey propName, TimeUnit defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
protected void putDefaultStringProperty(IClientConfigKey propName, String defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
protected void putDefaultBooleanProperty(IClientConfigKey propName, Boolean defaultValue) {
this.set(propName, defaultValue);
}
@Deprecated
String getDefaultPropName(String propName) {
return getNameSpace() + "." + propName;
}
public String getDefaultPropName(IClientConfigKey propName) {
return getDefaultPropName(propName.key());
}
public String getInstancePropName(String restClientName,
IClientConfigKey configKey) {
return getInstancePropName(restClientName, configKey.key());
}
public String getInstancePropName(String restClientName, String key) {
if (getNameSpace() == null) {
throw new NullPointerException("getNameSpace() may not be null");
}
return restClientName + "." + getNameSpace() + "." + key;
}
public DefaultClientConfigImpl withProperty(IClientConfigKey key, Object value) {
setProperty(key, value);
return this;
}
public static DefaultClientConfigImpl getEmptyConfig() {
return new DefaultClientConfigImpl();
}
public static DefaultClientConfigImpl getClientConfigWithDefaultValues(String clientName) {
return getClientConfigWithDefaultValues(clientName, DEFAULT_PROPERTY_NAME_SPACE);
}
public static DefaultClientConfigImpl getClientConfigWithDefaultValues() {
return getClientConfigWithDefaultValues("default", DEFAULT_PROPERTY_NAME_SPACE);
}
public static DefaultClientConfigImpl getClientConfigWithDefaultValues(String clientName, String nameSpace) {
DefaultClientConfigImpl config = new DefaultClientConfigImpl(nameSpace);
config.loadProperties(clientName);
return config;
}
} | 3,606 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/ResponseTimeWeightedRuleTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import java.net.URI;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.AbstractLoadBalancer;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
public class ResponseTimeWeightedRuleTest {
@Test
public void testServerWeights(){
try{
ConfigurationManager.loadPropertiesFromResources("sample-client.properties");
ConfigurationManager.getConfigInstance().setProperty(
"sample-client.ribbon.NFLoadBalancerClassName", "com.netflix.loadbalancer.DynamicServerListLoadBalancer");
ConfigurationManager.getConfigInstance().setProperty(
"sample-client.ribbon.NFLoadBalancerRuleClassName", "com.netflix.loadbalancer.WeightedResponseTimeRule");
// shorter weight adjusting interval
ConfigurationManager.getConfigInstance().setProperty(
"sample-client.ribbon." + WeightedResponseTimeRule.WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY, "5000");
ConfigurationManager.getConfigInstance().setProperty(
"sample-client.ribbon.InitializeNFLoadBalancer", "true");
RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
for (int i = 0; i < 20; i++) {
client.executeWithLoadBalancer(request);
}
System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats());
// wait for the weights to be adjusted
Thread.sleep(5000);
for (int i = 0; i < 50; i++) {
client.executeWithLoadBalancer(request);
}
System.out.println(((AbstractLoadBalancer) client.getLoadBalancer()).getLoadBalancerStats());
}
catch (Exception e){
e.printStackTrace();
}
}
}
| 3,607 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/GetPostTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.Random;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.http.HttpRequest.Verb;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.net.httpserver.HttpServer;
public class GetPostTest {
private static HttpServer server = null;
private static String SERVICE_URI;
private static RestClient client;
@BeforeClass
public static void init() throws Exception {
PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.http", "com.netflix.niws.client");
int port = (new Random()).nextInt(1000) + 4000;
SERVICE_URI = "http://localhost:" + port + "/";
try{
server = HttpServerFactory.create(SERVICE_URI, resourceConfig);
server.start();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
client = (RestClient) ClientFactory.getNamedClient("GetPostTest");
}
@AfterClass
public static void shutDown() {
server.stop(0);
}
@Test
public void testGet() throws Exception {
URI getUri = new URI(SERVICE_URI + "test/getObject");
MultivaluedMapImpl params = new MultivaluedMapImpl();
params.add("name", "test");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
HttpResponse response = client.execute(request);
assertEquals(200, response.getStatus());
assertTrue(response.getEntity(TestObject.class).name.equals("test"));
}
@Test
public void testPost() throws Exception {
URI getUri = new URI(SERVICE_URI + "test/setObject");
TestObject obj = new TestObject();
obj.name = "fromClient";
HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(getUri).entity(obj).build();
HttpResponse response = client.execute(request);
assertEquals(200, response.getStatus());
assertTrue(response.getEntity(TestObject.class).name.equals("fromClient"));
}
@Test
public void testChunkedEncoding() throws Exception {
String obj = "chunked encoded content";
URI postUri = new URI(SERVICE_URI + "test/postStream");
InputStream input = new ByteArrayInputStream(obj.getBytes("UTF-8"));
HttpRequest request = HttpRequest.newBuilder().verb(Verb.POST).uri(postUri).entity(input).build();
HttpResponse response = client.execute(request);
assertEquals(200, response.getStatus());
assertTrue(response.getEntity(String.class).equals(obj));
}
}
| 3,608 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureRestClientKeystoreTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import org.apache.commons.configuration.AbstractConfiguration;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.config.ConfigurationManager;
import com.sun.jersey.core.util.Base64;
/**
* Test keystore info is configurable/retrievable
*
* @author jzarfoss
*
*/
public class SecureRestClientKeystoreTest {
@Test
public void testGetKeystoreWithClientAuth() throws Exception{
// jks format
byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);
File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");
FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
try {
keystoreFileOut.write(dummyKeystore);
} finally {
keystoreFileOut.close();
}
FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
try {
truststoreFileOut.write(dummyTruststore);
} finally {
truststoreFileOut.close();
}
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = this.getClass().getName() + ".test1";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, tempTruststore.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, "changeit");
RestClient client = (RestClient) ClientFactory.getNamedClient(name);
KeyStore keyStore = client.getKeyStore();
Certificate cert = keyStore.getCertificate("ribbon_key");
assertNotNull(cert);
}
@Test
public void testGetKeystoreWithNoClientAuth() throws Exception{
// jks format
byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);
File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");
FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
try {
keystoreFileOut.write(dummyKeystore);
} finally {
keystoreFileOut.close();
}
FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
try {
truststoreFileOut.write(dummyTruststore);
} finally {
truststoreFileOut.close();
}
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = this.getClass().getName() + ".test2";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, "changeit");
RestClient client = (RestClient) ClientFactory.getNamedClient(name);
KeyStore keyStore = client.getKeyStore();
Certificate cert = keyStore.getCertificate("ribbon_key");
assertNotNull(cert);
}
}
| 3,609 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RetryTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.netflix.client.ClientException;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpRequest.Verb;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.testutil.MockHttpServer;
import com.netflix.config.ConfigurationManager;
import com.netflix.http4.MonitoredConnectionManager;
import com.netflix.http4.NFHttpClient;
import com.netflix.http4.NFHttpClientFactory;
import com.netflix.loadbalancer.AvailabilityFilteringRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.DummyPing;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerStats;
public class RetryTest {
@ClassRule
public static MockHttpServer server = new MockHttpServer()
;
private RestClient client;
private BaseLoadBalancer lb;
private NFHttpClient httpClient;
private MonitoredConnectionManager connectionPoolManager;
private static Server localServer;
@BeforeClass
public static void init() throws Exception {
// PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.client.http");
localServer = new Server("localhost", server.getServerPort());
}
@Before
public void beforeTest() {
ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.NFLoadBalancerClassName", BaseLoadBalancer.class.getName());
ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.client.NFLoadBalancerPingClassName", DummyPing.class.getName());
ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon.ReadTimeout", "1000");
ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.ConnectTimeout, "500");
ConfigurationManager.getConfigInstance().setProperty("RetryTest.ribbon." + CommonClientConfigKey.OkToRetryOnAllOperations, "true");
client = (RestClient) ClientFactory.getNamedClient("RetryTest");
lb = (BaseLoadBalancer) client.getLoadBalancer();
lb.setServersList(Lists.newArrayList(localServer));
httpClient = NFHttpClientFactory.getNamedNFHttpClient("RetryTest");
connectionPoolManager = (MonitoredConnectionManager) httpClient.getConnectionManager();
client.setMaxAutoRetries(0);
client.setMaxAutoRetriesNextServer(0);
client.setOkToRetryOnAllOperations(false);
lb.setServersList(Lists.newArrayList(localServer));
// reset the server index
lb.setRule(new AvailabilityFilteringRule());
lb.getLoadBalancerStats().getSingleServerStat(localServer).clearSuccessiveConnectionFailureCount();
}
@Test
public void testThrottled() throws Exception {
URI localUrl = new URI("/status?code=503");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0));
fail("Exception expected");
} catch (ClientException e) {
assertNotNull(e);
}
assertEquals(1, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
}
@Test
public void testThrottledWithRetrySameServer() throws Exception {
URI localUrl = new URI("/status?code=503");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
try {
client.executeWithLoadBalancer(request,
DefaultClientConfigImpl
.getEmptyConfig()
.set(CommonClientConfigKey.MaxAutoRetries, 1)
.set(CommonClientConfigKey.MaxAutoRetriesNextServer, 0));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
assertEquals(2, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
}
@Test
public void testThrottledWithRetryNextServer() throws Exception {
int connectionCount = connectionPoolManager.getConnectionsInPool();
URI localUrl = new URI("/status?code=503");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
System.out.println("Initial connections count " + connectionCount);
System.out.println("Final connections count " + connectionPoolManager.getConnectionsInPool());
// should be no connection leak
assertTrue(connectionPoolManager.getConnectionsInPool() <= connectionCount + 1);
}
@Test
public void testReadTimeout() throws Exception {
URI localUrl = new URI("/noresponse");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
}
@Test
public void testReadTimeoutWithRetriesNextServe() throws Exception {
URI localUrl = new URI("/noresponse");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
assertEquals(3, lb.getLoadBalancerStats().getSingleServerStat(localServer).getSuccessiveConnectionFailureCount());
}
@Test
public void postReadTimeout() throws Exception {
URI localUrl = new URI("/noresponse");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer);
assertEquals(1, stats.getSuccessiveConnectionFailureCount());
}
@Test
public void testRetriesOnPost() throws Exception {
URI localUrl = new URI("/noresponse");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build();
try {
client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer);
assertEquals(3, stats.getSuccessiveConnectionFailureCount());
}
@Test
public void testRetriesOnPostWithConnectException() throws Exception {
URI localUrl = new URI("/status?code=503");
lb.setServersList(Lists.newArrayList(localServer));
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).verb(Verb.POST).setRetriable(true).build();
try {
HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
fail("Exception expected");
} catch (ClientException e) { // NOPMD
}
ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(localServer);
assertEquals(3, stats.getSuccessiveConnectionFailureCount());
}
@Test
public void testSuccessfulRetries() throws Exception {
lb.setServersList(Lists.newArrayList(new Server("localhost:12987"), new Server("localhost:12987"), localServer));
URI localUrl = new URI("/ok");
HttpRequest request = HttpRequest.newBuilder().uri(localUrl).queryParams("name", "ribbon").build();
try {
HttpResponse response = client.executeWithLoadBalancer(request, DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.MaxAutoRetriesNextServer, 2));
assertEquals(200, response.getStatus());
} catch (ClientException e) {
fail("Unexpected exception");
}
ServerStats stats = lb.getLoadBalancerStats().getSingleServerStat(new Server("localhost:12987"));
assertEquals(1, stats.getSuccessiveConnectionFailureCount());
}
}
| 3,610 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/TestObject.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TestObject {
public String name;
}
| 3,611 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/RestClientTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.ClassRule;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.testutil.MockHttpServer;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
public class RestClientTest {
@ClassRule
public static MockHttpServer server = new MockHttpServer();
@ClassRule
public static MockHttpServer secureServer = new MockHttpServer().secure();
@Test
public void testExecuteWithoutLB() throws Exception {
RestClient client = (RestClient) ClientFactory.getNamedClient("google");
HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertStatusIsOk(response.getStatus());
response = client.execute(request);
assertStatusIsOk(response.getStatus());
}
@Test
public void testExecuteWithLB() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("allservices.ribbon." + CommonClientConfigKey.ReadTimeout, "10000");
ConfigurationManager.getConfigInstance().setProperty("allservices.ribbon." + CommonClientConfigKey.FollowRedirects, "true");
RestClient client = (RestClient) ClientFactory.getNamedClient("allservices");
BaseLoadBalancer lb = new BaseLoadBalancer();
Server[] servers = new Server[]{new Server("localhost", server.getServerPort())};
lb.addServers(Arrays.asList(servers));
client.setLoadBalancer(lb);
Set<URI> expected = new HashSet<URI>();
expected.add(new URI(server.getServerPath("/")));
Set<URI> result = new HashSet<URI>();
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
for (int i = 0; i < 5; i++) {
HttpResponse response = client.executeWithLoadBalancer(request);
assertStatusIsOk(response.getStatus());
assertTrue(response.isSuccess());
String content = response.getEntity(String.class);
response.close();
assertFalse(content.isEmpty());
result.add(response.getRequestedURI());
}
assertEquals(expected, result);
request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertEquals(200, response.getStatus());
}
@Test
public void testVipAsURI() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.DeploymentContextBasedVipAddresses", server.getServerPath("/"));
ConfigurationManager.getConfigInstance().setProperty("test1.ribbon.InitializeNFLoadBalancer", "false");
RestClient client = (RestClient) ClientFactory.getNamedClient("test1");
assertNull(client.getLoadBalancer());
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertStatusIsOk(response.getStatus());
assertEquals(server.getServerPath("/"), response.getRequestedURI().toString());
}
@Test
public void testSecureClient() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("test2.ribbon.IsSecure", "true");
RestClient client = (RestClient) ClientFactory.getNamedClient("test2");
HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertStatusIsOk(response.getStatus());
}
@Test
public void testSecureClient2() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.IsSecure, "true");
ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStore, secureServer.getTrustStore().getAbsolutePath());
ConfigurationManager.getConfigInstance().setProperty("test3.ribbon." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD);
RestClient client = (RestClient) ClientFactory.getNamedClient("test3");
BaseLoadBalancer lb = new BaseLoadBalancer();
Server[] servers = new Server[]{new Server("localhost", secureServer.getServerPort())};
lb.addServers(Arrays.asList(servers));
client.setLoadBalancer(lb);
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertStatusIsOk(response.getStatus());
assertEquals(secureServer.getServerPath("/"), response.getRequestedURI().toString());
}
@Test
public void testDelete() throws Exception {
RestClient client = (RestClient) ClientFactory.getNamedClient("google");
HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).build();
HttpResponse response = client.execute(request);
assertStatusIsOk(response.getStatus());
request = HttpRequest.newBuilder().uri(server.getServerURI()).verb(HttpRequest.Verb.DELETE).entity("").build();
response = client.execute(request);
assertStatusIsOk(response.getStatus());
}
private void assertStatusIsOk(int status) {
assertTrue(status == 200 || status == 302);
}
}
| 3,612 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/FollowRedirectTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
public class FollowRedirectTest {
private MockWebServer redirectingServer;
private MockWebServer redirectedServer;
@Before
public void setup() throws IOException {
redirectedServer = new MockWebServer();
redirectedServer.enqueue(new MockResponse()
.setResponseCode(200)
.setHeader("Content-type", "text/plain")
.setBody("OK"));
redirectingServer = new MockWebServer();
redirectedServer.play();
redirectingServer.enqueue(new MockResponse()
.setResponseCode(302)
.setHeader("Location", "http://localhost:" + redirectedServer.getPort()));
redirectingServer.play();
}
@After
public void shutdown() {
try {
redirectedServer.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
try {
redirectingServer.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testRedirectNotFollowed() throws Exception {
IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues("myclient");
config.set(CommonClientConfigKey.FollowRedirects, Boolean.FALSE);
ClientFactory.registerClientFromProperties("myclient", config);
RestClient client = (RestClient) ClientFactory.getNamedClient("myclient");
HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build();
HttpResponse response = client.executeWithLoadBalancer(request);
assertEquals(302, response.getStatus());
}
@Test
public void testRedirectFollowed() throws Exception {
IClientConfig config = DefaultClientConfigImpl
.getClientConfigWithDefaultValues("myclient2")
.set(IClientConfigKey.Keys.FollowRedirects, Boolean.TRUE);
ClientFactory.registerClientFromProperties("myclient2", config);
com.netflix.niws.client.http.RestClient client = (com.netflix.niws.client.http.RestClient) ClientFactory.getNamedClient("myclient2");
HttpRequest request = HttpRequest.newBuilder().uri(new URI("http://localhost:" + redirectingServer.getPort())).build();
HttpResponse response = client.execute(request);
assertEquals(200, response.getStatus());
}
}
| 3,613 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureAcceptAllGetTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.testutil.SimpleSSLTestServer;
import com.netflix.config.ConfigurationManager;
import com.sun.jersey.core.util.Base64;
import org.apache.commons.configuration.AbstractConfiguration;
import org.junit.*;
import org.junit.rules.TestName;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
*
* Test that the AcceptAllSocketFactory works against a dumbed down TLS server, except when it shouldn't...
*
* @author jzarfoss
*
*/
public class SecureAcceptAllGetTest {
private static String TEST_SERVICE_URI;
private static File TEST_FILE_KS;
private static File TEST_FILE_TS;
private static SimpleSSLTestServer TEST_SERVER;
@Rule
public TestName testName = new TestName();
@BeforeClass
public static void init() throws Exception {
// jks format
byte[] sampleTruststore1 = Base64.decode(SecureGetTest.TEST_TS1);
byte[] sampleKeystore1 = Base64.decode(SecureGetTest.TEST_KS1);
TEST_FILE_KS = File.createTempFile("SecureAcceptAllGetTest", ".keystore");
TEST_FILE_TS = File.createTempFile("SecureAcceptAllGetTest", ".truststore");
FileOutputStream keystoreFileOut = new FileOutputStream(TEST_FILE_KS);
try {
keystoreFileOut.write(sampleKeystore1);
} finally {
keystoreFileOut.close();
}
FileOutputStream truststoreFileOut = new FileOutputStream(TEST_FILE_TS);
try {
truststoreFileOut.write(sampleTruststore1);
} finally {
truststoreFileOut.close();
}
try {
TEST_SERVER = new SimpleSSLTestServer(TEST_FILE_TS, SecureGetTest.PASSWORD, TEST_FILE_KS, SecureGetTest.PASSWORD, false);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// setup server 1, will use first keystore/truststore with client auth
TEST_SERVICE_URI = "https://127.0.0.1:" + TEST_SERVER.getPort() + "/";
}
@AfterClass
public static void shutDown(){
try{
TEST_SERVER.close();
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testPositiveAcceptAllSSLSocketFactory() throws Exception{
// test connection succeeds connecting to a random SSL endpoint with allow all SSL factory
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest." + testName.getMethodName();
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory");
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
TEST_SERVER.accept();
URI getUri = new URI(TEST_SERVICE_URI + "test/");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
HttpResponse response = rc.execute(request);
assertEquals(200, response.getStatus());
}
@Test
public void testNegativeAcceptAllSSLSocketFactoryCannotWorkWithTrustStore() throws Exception{
// test config exception happens before we even try to connect to anything
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest." + testName.getMethodName();
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.CustomSSLSocketFactoryClassName, "com.netflix.http4.ssl.AcceptAllSocketFactory");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, TEST_FILE_TS.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, SecureGetTest.PASSWORD);
boolean foundCause = false;
try {
ClientFactory.getNamedClient(name);
} catch(Throwable t){
while (t != null && ! foundCause){
if (t instanceof IllegalArgumentException && t.getMessage().startsWith("Invalid value for property:CustomSSLSocketFactoryClassName")){
foundCause = true;
break;
}
t = t.getCause();
}
}
assertTrue(foundCause);
}
@Test
public void testNegativeAcceptAllSSLSocketFactory() throws Exception{
// test exception is thrown connecting to a random SSL endpoint without explicitly setting factory to allow all
String name = "GetPostSecureTest." + testName.getMethodName();
// don't set any interesting properties -- really we're just setting the defaults
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
TEST_SERVER.accept();
URI getUri = new URI(TEST_SERVICE_URI + "test/");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
boolean foundCause = false;
try {
rc.execute(request);
} catch(Throwable t){
while (t != null && ! foundCause){
if (t instanceof SSLPeerUnverifiedException && t.getMessage().startsWith("peer not authenticated")){
foundCause = true;
break;
}
t = t.getCause();
}
}
assertTrue(foundCause);
}
}
| 3,614 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/TestResource.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import java.io.InputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
@Produces({"application/xml"})
@Path("/test")
public class TestResource {
@Path("/getObject")
@GET
public Response getObject(@QueryParam ("name") String name) {
TestObject obj = new TestObject();
obj.name = name;
return Response.ok(obj).build();
}
@Path("/getJsonObject")
@Produces("application/json")
@GET
public Response getJsonObject(@QueryParam ("name") String name) throws Exception {
TestObject obj = new TestObject();
obj.name = name;
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(obj);
return Response.ok(value).build();
}
@Path("/setObject")
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response setObject(TestObject obj) {
return Response.ok(obj).build();
}
@Path("/setJsonObject")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response setJsonObject(String obj) throws Exception {
System.out.println("Get json string " + obj);
return Response.ok(obj).build();
}
@POST
@Path("/postStream")
@Consumes( { MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML})
public Response handlePost(final InputStream in, @HeaderParam("Transfer-Encoding") String transferEncoding) {
try {
byte[] bytes = IOUtils.toByteArray(in);
String entity = new String(bytes, "UTF-8");
return Response.ok(entity).build();
} catch (Exception e) {
return Response.serverError().build();
}
}
@GET
@Path("/get503")
public Response get503() {
return Response.status(503).build();
}
@GET
@Path("/get500")
public Response get500() {
return Response.status(500).build();
}
@GET
@Path("/getReadtimeout")
public Response getReadtimeout() {
try {
Thread.sleep(10000);
} catch (Exception e) { // NOPMD
}
return Response.ok().build();
}
@POST
@Path("/postReadtimeout")
public Response postReadtimeout() {
try {
Thread.sleep(10000);
} catch (Exception e) { // NOPMD
}
return Response.ok().build();
}
}
| 3,615 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/SecureGetTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import org.apache.commons.configuration.AbstractConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.testutil.SimpleSSLTestServer;
import com.netflix.config.ConfigurationManager;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.core.util.MultivaluedMapImpl;
/**
*
* Test TLS configurations work against a very dumbed down test server.
*
* @author jzarfoss
*
*/
public class SecureGetTest {
// custom minted test keystores/truststores for Ribbon testing
// PLEASE DO NOT USE FOR ANYTHING OTHER THAN TESTING (the private keys are sitting right here in a String!!)
// but if you need keystore to test with, help yourself, they're good until 2113!
// we have a pair of independently valid keystore/truststore combinations
// thus allowing us to perform both positive and negative testing,
// the negative testing being that set 1 and set 2 cannot talk to each other
// base64 encoded
// Keystore type: JKS
// Keystore provider: SUN
//
// Your keystore contains 1 entry
//
// Alias name: ribbon_root
// Creation date: Sep 6, 2013
// Entry type: trustedCertEntry
//
// Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1
// Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1
// Serial number: 1
// Valid from: Fri Sep 06 10:25:22 PDT 2013 until: Sun Aug 13 10:25:22 PDT 2113
// Certificate fingerprints:
// MD5: BD:08:2A:F3:3B:26:C0:D4:44:B9:6D:EE:D2:45:31:C0
// SHA1: 64:95:7E:C6:0C:D7:81:56:28:0C:93:60:85:AB:9D:E2:60:33:70:43
// Signature algorithm name: SHA1withRSA
// Version: 3
//
// Extensions:
//
// #1: ObjectId: 2.5.29.19 Criticality=false
// BasicConstraints:[
// CA:true
// PathLen:2147483647
// ]
public static final String TEST_TS1 =
"/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E6KkQAFWC41MDkAAAIyMIICLjCCAZeg" +
"AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDExCzAJBgNV" +
"BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" +
"OTA2MTcyNTIyWhgPMjExMzA4MTMxNzI1MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MTEL" +
"MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" +
"nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAg8riOgT2Y39SQlZE+MWnOiKjREZzQ3ecvPf40oF8" +
"9YPNGpBhJzIKdA0TR1vQ70p3Fl2+Y5txs1H2/iguOdFMBrSdv1H8qJG1UufaeYO++HBm3Mi2L02F" +
"6fcTEEyXQMebKCWf04mxvLy5M6B5yMqZ9rHEZD+qsF4rXspx70bd0tUCAwEAAaMQMA4wDAYDVR0T" +
"BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBzTEn9AZniODYSRa+N7IvZu127rh+Sc6XWth68TBRj" +
"hThDFARnGxxe2d3EFXB4xH7qcvLl3HQ3U6lIycyLabdm06D3/jzu68mkMToE5sHJmrYNHHTVl0aj" +
"0gKFBQjLRJRlgJ3myUbbfrM+/a5g6S90TsVGTxXwFn5bDvdErsn8F8Hd41plMkW5ywsn6yFZMaFr" +
"MxnX";
// Keystore type: JKS
// Keystore provider: SUN
//
// Your keystore contains 1 entry
//
// Alias name: ribbon_root
// Creation date: Sep 6, 2013
// Entry type: trustedCertEntry
//
// Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2
// Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2
// Serial number: 1
// Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113
// Certificate fingerprints:
// MD5: 44:64:E3:25:4F:D2:2C:8D:4D:B0:53:19:59:BD:B3:20
// SHA1: 26:2F:41:6D:03:C7:D0:8E:4F:AF:0E:4F:29:E3:08:53:B7:3C:DB:EE
// Signature algorithm name: SHA1withRSA
// Version: 3
//
// Extensions:
//
// #1: ObjectId: 2.5.29.19 Criticality=false
// BasicConstraints:[
// CA:true
// PathLen:2147483647
// ]
public static final String TEST_TS2 =
"/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E92vgAFWC41MDkAAAIyMIICLjCCAZeg" +
"AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDIxCzAJBgNV" +
"BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" +
"OTA2MTcyNjIyWhgPMjExMzA4MTMxNzI2MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MjEL" +
"MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" +
"nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAnEwAfuHYKRJviVB3RyV3+/mp4qjWZZd/q+fE2Z0k" +
"o2N2rrC8fAw53KXwGOE5fED6wXd3B2zyoSFHVsWOeL+TUoohn+eHSfwH7xK+0oWC8IvUoXWehOft" +
"grYtv9Jt5qNY5SmspBmyxFiaiAWQJYuf12Ycu4Gqg+P7mieMHgu6Do0CAwEAAaMQMA4wDAYDVR0T" +
"BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBNA0ask9eTYYhYA3bbmQZInxkBV74Gq/xorLlVygjn" +
"OgyGYp4/L274qwlPMqnQRmVbezkug2YlUK8xbrjwCUvHq2XW38e2RjK5q3EXVkGJxgCBuHug/eIf" +
"wD+/IEIE8aVkTW2j1QrrdkXDhRO5OsjvIVdy5/V4U0hVDnSo865ud9VQ/hZmOQuZItHViSoGSe2j" +
"bbZk";
// Keystore type: JKS
// Keystore provider: SUN
//
// Your keystore contains 1 entry
//
// Alias name: ribbon_key
// Creation date: Sep 6, 2013
// Entry type: PrivateKeyEntry
// Certificate chain length: 1
// Certificate[1]:
// Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity1
// Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1
// Serial number: 64
// Valid from: Fri Sep 06 10:25:22 PDT 2013 until: Sun Aug 13 10:25:22 PDT 2113
// Certificate fingerprints:
// MD5: 79:C5:F3:B2:B8:4C:F2:3F:2E:C7:67:FC:E7:04:BF:90
// SHA1: B1:D0:4E:A6:D8:84:BF:8B:01:46:B6:EA:97:5B:A0:4E:13:8B:A9:DE
// Signature algorithm name: SHA1withRSA
// Version: 3
public static final String TEST_KS1 =
"/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0Toq4AAACuzCCArcwDgYKKwYBBAEqAhEB" +
"AQUABIICo9fLN8zeXLcyx50+6B6gdXiUslZKY0SgLwL8kKNlQFiccD3Oc1yWjMnVC2QOdLsFzcVk" +
"ROhgMH/nHfFeXFlvY5IYMXqhbEC37LjE52RtX5KHv4FLYxxZCHduAwO8UTPa603XzrJ0VTMJ6Hso" +
"9+Ql76cGxPtIPcYm8IfqIY22as3NlKO4eMbiur9GLvuC57eql8vROaxGy8y657gc6kZMUyQOC+HG" +
"a5M3DTFpjl4V6HHbXHhMNEk9eXHnrZwYVOJmOgdgIrNNHOyD4kE+k21C7rUHhLAwK84wKL/tW4k9" +
"xnhOJK/L1RmycRIFWwXVi3u/3vi49bzdZsRLn73MdQkTe5p8oNZzG9sxg76u67ua6+99TMZYE1ay" +
"5JCYgbr85KbRsoX9Hd5XBcSNzROKJl0To2tAF8eTTMRlhEy7JZyTF2M9877juNaregVwE3Tp+a/J" +
"ACeNMyrxOQItNDam7a5dgBohpM8oJdEFqqj/S9BU7H5sR0XYo8TyIe1BV9zR5ZC/23fj5l5zkrri" +
"TCMgMbvt95JUGOT0gSzxBMmhV+ZLxpmVz3M5P2pXX0DXGTKfuHSiBWrh1GAQL4BOVpuKtyXlH1/9" +
"55/xY25W0fpLzMiQJV7jf6W69LU0FAFWFH9uuwf/sFph0S1QQXcQSfpYmWPMi1gx/IgIbvT1xSuI" +
"6vajgFqv6ctiVbFAJ6zmcnGd6e33+Ao9pmjs5JPZP3rtAYd6+PxtlwUbGLZuqIVK4o68LEISDfvm" +
"nGlk4/1+S5CILKVqTC6Ja8ojwUjjsNSJbZwHue3pOkmJQUNtuK6kDOYXgiMRLURbrYLyen0azWw8" +
"C5/nPs5J4pN+irD/hhD6cupCnUJmzMw30u8+LOCN6GaM5fdCTQ2uQKF7quYuD+gR3lLNOqq7KAAA" +
"AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" +
"UmliYm9uVGVzdFJvb3QxMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" +
"Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjUyMloYDzIxMTMwODEzMTcyNTIyWjBYMR0wGwYD" +
"VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MTELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" +
"CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAydqk" +
"AJuUcSF8dpUbNJWl+G1usgHtEFEbOMm54N/ZqGC7iSYs6EXfeoEyiHrMw/hdCKACERq2vuiuqan8" +
"h6z65/DXIiHUyykGb/Z4NK1I0aCQLZG4Ek3sERilILWyy2NRpjUrvqDPr/mQgymXqpuYhSD81jHx" +
"F84AOpTrnGsY7/sCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAjvtRKNhb1R6XIuWaOxJ0XDLine464" +
"Ie7LDfkE/KB43oE4MswjRh7nR9q6C73oa6TlIXmW6ysyKPp0vAyWHlq/zZhL3gNQ6faHuYHqas5s" +
"nJQgvQpHAQh4VXRyZt1K8ZdsHg3Qbd4APTL0aRVQkxDt+Dxd6AsoRMKmO/c5CRwUFIV/CK7k5VSh" +
"Sl5PRtH3PVj2vp84";
// Keystore type: JKS
// Keystore provider: SUN
//
// Your keystore contains 1 entry
//
// Alias name: ribbon_key
// Creation date: Sep 6, 2013
// Entry type: PrivateKeyEntry
// Certificate chain length: 1
// Certificate[1]:
// Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity2
// Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2
// Serial number: 64
// Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113
// Certificate fingerprints:
// MD5: C3:AF:6A:DB:18:ED:70:22:83:73:9A:A5:DB:58:6D:04
// SHA1: B7:D4:F0:87:A8:4E:49:0A:91:B1:7B:62:28:CA:A2:4A:0E:AE:40:CC
// Signature algorithm name: SHA1withRSA
// Version: 3
//
//
//
public static final String TEST_KS2 =
"/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0T3bNAAACuzCCArcwDgYKKwYBBAEqAhEB" +
"AQUABIICoysDP4inwmxxKZkS8EYMW3DCJCD1AmpwFHxJIzo2v9fMysg+vjKxsrvVyKG23ZcHcznI" +
"ftmrEpriCCUZp+NNAf0EJWVAIzGenwrsd0+rI5I96gBOh9slJUzgucn7164R3XKNKk+VWcwGJRh+" +
"IuHxVrwFN025pfhlBJXNGJg4ZlzB7ZwcQPYblBzhLbhS3vJ1Vc46pEYWpnjxmHaDSetaQIcueAp8" +
"HnTUkFMXJ6t51N0u9QMPhBH7p7N8tNjaa5noSdxhSl/2Znj6r04NwQU1qX2n4rSWEnYaW1qOVkgx" +
"YrQzxI2kSHZfQDM2T918UikboQvAS1aX4h5P3gVCDKLr3EOO6UYO0ZgLHUr/DZrhVKd1KAhnzaJ8" +
"BABxot2ES7Zu5EzY9goiaYDA2/bkURmt0zDdKpeORb7r59XBZUm/8D80naaNnE45W/gBA9bCiDu3" +
"R99xie447c7ZX9Jio25yil3ncv+npBO1ozc5QIgQnbEfxbbwii3//shvPT6oxYPrcwWBXnaJNC5w" +
"2HDpCTXJZNucyjnNVVxC7p1ANNnvvZhgC0+GpEqmf/BW+fb9Qu+AXe0/h4Vnoe/Zs92vPDehpaKy" +
"oe+jBlUNiW2bpR88DSqxVcIu1DemlgzPa1Unzod0FdrOr/272bJnB2zAo4OBaBSv3KNf/rsMKjsU" +
"X2Po77+S+PKoQkqd8KJFpmLEb0vxig9JsrTDJXLf4ebeSA1W7+mBotimMrp646PA3NciMSbS4csh" +
"A7o/dBYhHlEosVgThm1JknIKhemf+FZsOzR3bJDT1oXJ/GhYpfzlCLyVFBeVP0KRnhih4xO0MEO7" +
"Q21DBaTTqAvUo7Iv3/F3mGMOanLcLgoRoq3moQ7FhfCDRtRAPA1qT2+pxPG5wqlGeYc6McOvogAA" +
"AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" +
"UmliYm9uVGVzdFJvb3QyMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" +
"Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjYyMloYDzIxMTMwODEzMTcyNjIyWjBYMR0wGwYD" +
"VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MjELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" +
"CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtOvK" +
"fBMC/oMo4xf4eYGN7hTNn+IywaSaVYndqECIfuznoIqRKSbeCKPSGs4CN1D+u3E2UoXcsDmTguHU" +
"fokDA7sLUu8wD5ndAXfCkP3gXlFtUpNz/jPaXDsMFntTn2BdLKccxRxNwtwC0zzwIdtx9pw/Ru0g" +
"NXIQnPi50aql5WcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQCYWM2ZdBjG3jCvMw/RkebMLkEDRxVM" +
"XU63Ygo+iCZUk8V8d0/S48j8Nk/hhVGHljsHqE/dByEF77X6uHaDGtt3Xwe+AYPofoJukh89jKnT" +
"jEDtLF+y5AVfz6b2z3TnJcuigMr4ZtBFv18R00KLnVAznl/waXG8ix44IL5ss6nRZBJE4jr+ZMG9" +
"9I4P1YhySxo3Qd3g";
private static String SERVICE_URI1;
private static String SERVICE_URI2;
private static SimpleSSLTestServer testServer1;
private static SimpleSSLTestServer testServer2;
private static File FILE_TS1;
private static File FILE_KS1;
private static File FILE_TS2;
private static File FILE_KS2;
public static final String PASSWORD = "changeit";
@BeforeClass
public static void init() throws Exception {
// setup server 1, will use first keystore/truststore with client auth
// jks format
byte[] sampleTruststore1 = Base64.decode(TEST_TS1);
byte[] sampleKeystore1 = Base64.decode(TEST_KS1);
FILE_KS1 = File.createTempFile("SecureGetTest1", ".keystore");
FILE_TS1 = File.createTempFile("SecureGetTest1", ".truststore");
FileOutputStream keystoreFileOut = new FileOutputStream(FILE_KS1);
try {
keystoreFileOut.write(sampleKeystore1);
} finally {
keystoreFileOut.close();
}
FileOutputStream truststoreFileOut = new FileOutputStream(FILE_TS1);
try {
truststoreFileOut.write(sampleTruststore1);
} finally {
truststoreFileOut.close();
}
try{
testServer1 = new SimpleSSLTestServer(FILE_TS1, PASSWORD, FILE_KS1, PASSWORD, true);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
SERVICE_URI1 = "https://127.0.0.1:" + testServer1.getPort() + "/";
// setup server 2, will use second keystore truststore without client auth
// jks format
byte[] sampleTruststore2 = Base64.decode(TEST_TS2);
byte[] sampleKeystore2 = Base64.decode(TEST_KS2);
FILE_KS2 = File.createTempFile("SecureGetTest2", ".keystore");
FILE_TS2 = File.createTempFile("SecureGetTest2", ".truststore");
keystoreFileOut = new FileOutputStream(FILE_KS2);
try {
keystoreFileOut.write(sampleKeystore2);
} finally {
keystoreFileOut.close();
}
truststoreFileOut = new FileOutputStream(FILE_TS2);
try {
truststoreFileOut.write(sampleTruststore2);
} finally {
truststoreFileOut.close();
}
try{
testServer2 = new SimpleSSLTestServer(FILE_TS2, PASSWORD, FILE_KS2, PASSWORD, false);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
SERVICE_URI2 = "https://127.0.0.1:" + testServer2.getPort() + "/";
}
@AfterClass
public static void shutDown(){
try{
testServer1.close();
}catch(Exception e){
e.printStackTrace();
}
try{
testServer2.close();
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testSunnyDay() throws Exception {
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest" + ".testSunnyDay";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer1.getPort()));
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
testServer1.accept();
URI getUri = new URI(SERVICE_URI1 + "test/");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
HttpResponse response = rc.execute(request);
assertEquals(200, response.getStatus());
}
@Test
public void testSunnyDayNoClientAuth() throws Exception{
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest" + ".testSunnyDayNoClientAuth";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS2.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
testServer2.accept();
URI getUri = new URI(SERVICE_URI2 + "test/");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
HttpResponse response = rc.execute(request);
assertEquals(200, response.getStatus());
}
@Test
public void testFailsWithHostNameValidationOn() throws Exception {
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest" + ".testFailsWithHostNameValidationOn";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "true"); // <--
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsClientAuthRequired, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStore, FILE_KS1.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.KeyStorePassword, PASSWORD);
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath());
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
testServer1.accept();
URI getUri = new URI(SERVICE_URI1 + "test/");
MultivaluedMapImpl params = new MultivaluedMapImpl();
params.add("name", "test");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
try{
rc.execute(request);
fail("expecting ssl hostname validation error");
}catch(ClientHandlerException che){
assertTrue(che.getMessage().indexOf("hostname in certificate didn't match") > -1);
}
}
@Test
public void testClientRejectsWrongServer() throws Exception{
AbstractConfiguration cm = ConfigurationManager.getConfigInstance();
String name = "GetPostSecureTest" + ".testClientRejectsWrongServer";
String configPrefix = name + "." + "ribbon";
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsSecure, "true");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.SecurePort, Integer.toString(testServer2.getPort()));
cm.setProperty(configPrefix + "." + CommonClientConfigKey.IsHostnameValidationRequired, "false");
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStore, FILE_TS1.getAbsolutePath()); // <--
cm.setProperty(configPrefix + "." + CommonClientConfigKey.TrustStorePassword, PASSWORD);
RestClient rc = (RestClient) ClientFactory.getNamedClient(name);
testServer2.accept();
URI getUri = new URI(SERVICE_URI2 + "test/");
HttpRequest request = HttpRequest.newBuilder().uri(getUri).queryParams("name", "test").build();
try{
rc.execute(request);
fail("expecting ssl hostname validation error");
}catch(ClientHandlerException che){
assertTrue(che.getMessage().indexOf("peer not authenticated") > -1);
}
}
}
| 3,616 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/niws/client/http/PrimeConnectionsTest.java | package com.netflix.niws.client.http;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.commons.configuration.Configuration;
import org.junit.*;
import com.netflix.client.ClientFactory;
import com.netflix.client.PrimeConnections.PrimeConnectionEndStats;
//import com.netflix.client.PrimeConnections.PrimeConnectionEndStats;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.AbstractServerList;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.net.httpserver.HttpServer;
public class PrimeConnectionsTest {
private static String SERVICE_URI;
private static int port = (new Random()).nextInt(1000) + 4000;
private static HttpServer server = null;
private static final int SMALL_FIXED_SERVER_LIST_SIZE = 10;
private static final int LARGE_FIXED_SERVER_LIST_SIZE = 200;
public static class LargeFixedServerList extends FixedServerList {
public LargeFixedServerList() {
super(200);
}
}
public static class SmallFixedServerList extends FixedServerList {
public SmallFixedServerList() {
super(10);
}
}
public static class FixedServerList extends AbstractServerList<Server> {
private Server testServer = new Server("localhost", port);
private List<Server> testServers;
public FixedServerList(int repeatCount) {
Server list[] = new Server[repeatCount];
for (int ii = 0; ii < list.length; ii++) {
list[ii] = testServer;
}
testServers = Arrays.asList(list);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
@Override
public List<Server> getInitialListOfServers() {
return testServers;
}
@Override
public List<Server> getUpdatedListOfServers() {
return testServers;
}
}
@BeforeClass
public static void setup(){
PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.niws.client.http");
SERVICE_URI = "http://localhost:" + port + "/";
try{
server = HttpServerFactory.create(SERVICE_URI, resourceConfig);
server.start();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testPrimeConnectionsSmallPool() throws Exception {
Configuration config = ConfigurationManager.getConfigInstance();
config.setProperty("PrimeConnectionsTest1.ribbon.NFLoadBalancerClassName",
com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
config.setProperty("PrimeConnectionsTest1.ribbon.NIWSServerListClassName", SmallFixedServerList.class.getName());
config.setProperty("PrimeConnectionsTest1.ribbon.EnablePrimeConnections", "true");
DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest1");
PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats();
assertEquals(stats.success, SMALL_FIXED_SERVER_LIST_SIZE);
}
@Test
public void testPrimeConnectionsLargePool() throws Exception {
Configuration config = ConfigurationManager.getConfigInstance();
config.setProperty("PrimeConnectionsTest2.ribbon.NFLoadBalancerClassName",
com.netflix.loadbalancer.DynamicServerListLoadBalancer.class.getName());
config.setProperty("PrimeConnectionsTest2.ribbon.NIWSServerListClassName", LargeFixedServerList.class.getName());
config.setProperty("PrimeConnectionsTest2.ribbon.EnablePrimeConnections", "true");
DynamicServerListLoadBalancer<Server> lb = (DynamicServerListLoadBalancer<Server>) ClientFactory.getNamedLoadBalancer("PrimeConnectionsTest2");
PrimeConnectionEndStats stats = lb.getPrimeConnections().getEndStats();
assertEquals(stats.success, LARGE_FIXED_SERVER_LIST_SIZE);
}
@AfterClass
public static void shutDown() {
server.stop(0);
}
}
| 3,617 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/http4/NFHttpClientTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import com.netflix.client.testutil.MockHttpServer;
public class NFHttpClientTest {
@ClassRule
public static MockHttpServer server = new MockHttpServer();
@Test
public void testDefaultClient() throws Exception {
NFHttpClient client = NFHttpClientFactory.getDefaultClient();
HttpGet get = new HttpGet(server.getServerURI()); // uri
// this is not the overridable method
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String contentStr = EntityUtils.toString(entity);
assertTrue(contentStr.length() > 0);
}
@Test
public void testNFHttpClient() throws Exception {
NFHttpClient client = NFHttpClientFactory.getNFHttpClient("localhost", server.getServerPort());
ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager();
cm.setDefaultMaxPerRoute(10);
HttpGet get = new HttpGet(server.getServerURI());
ResponseHandler<Integer> respHandler = new ResponseHandler<Integer>(){
public Integer handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String contentStr = EntityUtils.toString(entity);
return contentStr.length();
}
};
long contentLen = client.execute(get, respHandler);
assertTrue(contentLen > 0);
}
@Ignore
public void testMultiThreadedClient() throws Exception {
NFHttpClient client = (NFHttpClient) NFHttpClientFactory
.getNFHttpClient("hc.apache.org", 80);
ThreadSafeClientConnManager cm = (ThreadSafeClientConnManager) client.getConnectionManager();
cm.setDefaultMaxPerRoute(10);
HttpHost target = new HttpHost("hc.apache.org", 80);
// create an array of URIs to perform GETs on
String[] urisToGet = { "/", "/httpclient-3.x/status.html",
"/httpclient-3.x/methods/",
"http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/" };
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet get = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(client, target, get, i + 1);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
}
/**
* A thread that performs a GET.
*/
static class GetThread extends Thread {
private HttpClient httpClient;
private HttpHost target;
private HttpGet request;
private int id;
public GetThread(HttpClient httpClient, HttpHost target, HttpGet request, int id) {
this.httpClient = httpClient;
this.target = target;
this.request = request;
this.id = id;
}
/**
* Executes the GetMethod and prints some satus information.
*/
public void run() {
try {
System.out.println(id + " - about to get something from " + request.getURI());
// execute the method
HttpResponse resp = httpClient.execute(target, request);
System.out.println(id + " - get executed");
// get the response body as an array of bytes
byte[] bytes = EntityUtils.toByteArray(resp.getEntity());
System.out.println(id + " - " + bytes.length + " bytes read");
} catch (Exception e) {
System.out.println(id + " - error: " + e);
} finally {
System.out.println(id + " - connection released");
}
}
}
}
| 3,618 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/http4/NamedConnectionPoolTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;
import org.junit.ClassRule;
import org.junit.Test;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.testutil.MockHttpServer;
import com.netflix.config.ConfigurationManager;
import com.netflix.niws.client.http.RestClient;
public class NamedConnectionPoolTest {
@ClassRule
public static MockHttpServer server = new MockHttpServer();
@Test
public void testConnectionPoolCounters() throws Exception {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
NFHttpClient client = NFHttpClientFactory.getNamedNFHttpClient("google-NamedConnectionPoolTest");
assertTrue(client.getConnectionManager() instanceof MonitoredConnectionManager);
MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) client.getConnectionManager();
connectionPoolManager.setDefaultMaxPerRoute(100);
connectionPoolManager.setMaxTotal(200);
assertTrue(connectionPoolManager.getConnectionPool() instanceof NamedConnectionPool);
NamedConnectionPool connectionPool = (NamedConnectionPool) connectionPoolManager.getConnectionPool();
System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
System.out.println("Requests count: " + connectionPool.getRequestsCount());
System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
System.out.println("Deleted :" + connectionPool.getDeleteCount());
System.out.println("Released: " + connectionPool.getReleaseCount());
for (int i = 0; i < 10; i++) {
HttpUriRequest request = new HttpGet(server.getServerPath("/"));
HttpResponse response = client.execute(request);
EntityUtils.consume(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
assertTrue(statusCode == 200 || statusCode == 302);
Thread.sleep(500);
}
System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
System.out.println("Requests count: " + connectionPool.getRequestsCount());
System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
System.out.println("Deleted :" + connectionPool.getDeleteCount());
System.out.println("Released: " + connectionPool.getReleaseCount());
assertTrue(connectionPool.getCreatedEntryCount() >= 1);
assertTrue(connectionPool.getRequestsCount() >= 10);
assertTrue(connectionPool.getFreeEntryCount() >= 9);
assertEquals(0, connectionPool.getDeleteCount());
assertEquals(connectionPool.getReleaseCount(), connectionPool.getRequestsCount());
assertEquals(connectionPool.getRequestsCount(), connectionPool.getCreatedEntryCount() + connectionPool.getFreeEntryCount());
ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxTotalHttpConnections.key(), "50");
ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), "10");
assertEquals(50, connectionPoolManager.getMaxTotal());
assertEquals(10, connectionPoolManager.getDefaultMaxPerRoute());
}
@Test
public void testConnectionPoolCleaner() throws Exception {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, "100");
ConfigurationManager.getConfigInstance().setProperty("ConnectionPoolCleanerTest.ribbon." + CommonClientConfigKey.ConnectionCleanerRepeatInterval, "500");
RestClient client = (RestClient) ClientFactory.getNamedClient("ConnectionPoolCleanerTest");
NFHttpClient httpclient = NFHttpClientFactory.getNamedNFHttpClient("ConnectionPoolCleanerTest");
assertNotNull(httpclient);
com.netflix.client.http.HttpResponse response = null;
try {
response = client.execute(HttpRequest.newBuilder().uri(server.getServerPath("/")).build());
} finally {
if (response != null) {
response.close();
}
}
MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) httpclient.getConnectionManager();
Thread.sleep(2000);
assertEquals(0, connectionPoolManager.getConnectionsInPool());
client.shutdown();
}
}
| 3,619 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client/ClientFactoryTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ConfigurationBasedServerList;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.client.http.RestClient;
public class ClientFactoryTest {
private static RestClient client;
@BeforeClass
public static void init() {
ConfigurationManager.getConfigInstance().setProperty("junit.ribbon.listOfServers", "www.example1.come:80,www.example2.come:80,www.example3.come:80");
client = (RestClient) ClientFactory.getNamedClient("junit");
}
@Test
public void testChooseServers() {
assertNotNull(client);
DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) client.getLoadBalancer();
assertTrue(lb.getServerListImpl() instanceof ConfigurationBasedServerList);
Set<Server> expected = new HashSet<Server>();
expected.add(new Server("www.example1.come:80"));
expected.add(new Server("www.example2.come:80"));
expected.add(new Server("www.example3.come:80"));
Set<Server> result = new HashSet<Server>();
for (int i = 0; i <= 10; i++) {
Server s = lb.chooseServer();
result.add(s);
}
assertEquals(expected, result);
}
}
| 3,620 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client/ManyShortLivedRequestsSurvivorTest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client;
import com.google.mockwebserver.MockResponse;
import com.google.mockwebserver.MockWebServer;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.niws.client.http.RestClient;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import static com.netflix.config.ConfigurationManager.getConfigInstance;
public class ManyShortLivedRequestsSurvivorTest {
@Test
public void survive() throws IOException, ClientException, URISyntaxException, InterruptedException {
String clientName = "RibbonClientTest-loadBalancingDefaultPolicyRoundRobin";
String serverListKey = clientName + ".ribbon.listOfServers";
int nbHitsPerServer = 60;
MockWebServer server1 = new MockWebServer();
MockWebServer server2 = new MockWebServer();
for (int i = 0; i < nbHitsPerServer; i++) {
server1.enqueue(new MockResponse().setResponseCode(200).setBody("server1 success <" + i + ">!"));
server2.enqueue(new MockResponse().setResponseCode(200).setBody("server2 success <" + i + ">!"));
}
server1.play();
server2.play();
getConfigInstance().setProperty(serverListKey, hostAndPort(server1.getUrl("")) + "," + hostAndPort(server2.getUrl("")));
RestClient client = (RestClient) ClientFactory.getNamedClient(clientName);
HttpRequest request;
for (int i = 0; i < nbHitsPerServer * 2; i++) {
request = HttpRequest.newBuilder().uri(new URI("/")).build();
HttpResponse response = client.executeWithLoadBalancer(request);
response.close();
}
}
static String hostAndPort(URL url) {
return "localhost:" + url.getPort();
}
}
| 3,621 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client/samples/SampleApp.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client.samples;
import java.net.URI;
import org.junit.Ignore;
import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.client.http.RestClient;
@Ignore
public class SampleApp {
public static void main(String[] args) throws Exception {
ConfigurationManager.loadPropertiesFromResources("sample-client.properties"); // 1
System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));
RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client"); // 2
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); // 3
for (int i = 0; i < 20; i++) {
HttpResponse response = client.executeWithLoadBalancer(request); // 4
System.out.println("Status code for " + response.getRequestedURI() + " :" + response.getStatus());
}
ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
System.out.println(lb.getLoadBalancerStats());
ConfigurationManager.getConfigInstance().setProperty(
"sample-client.ribbon.listOfServers", "www.linkedin.com:80,www.google.com:80"); // 5
System.out.println("changing servers ...");
Thread.sleep(3000); // 6
for (int i = 0; i < 20; i++) {
HttpResponse response = client.executeWithLoadBalancer(request);
System.out.println("Status code for " + response.getRequestedURI() + " : " + response.getStatus());
}
System.out.println(lb.getLoadBalancerStats()); // 7
}
}
| 3,622 |
0 | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/test/java/com/netflix/client/testutil/SimpleSSLTestServer.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client.testutil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.TrustManagerFactory;
import org.junit.Ignore;
import com.google.common.io.Closeables;
/**
*
* A simple SSL(TLS) server for which we can test against
* to ensure that the SSL connection can (or cannot) be established.
*
* @author jzarfoss
*
*/
@Ignore
public class SimpleSSLTestServer {
private static final String NL = System.getProperty("line.separator");
private static final String CANNED_RESPONSE =
"HTTP/1.0 200 OK" + NL +
"Content-Type: text/plain" + NL +
"Content-Length: 5" + NL + NL +
"hello" + NL;
private final ServerSocket ss;
@edu.umd.cs.findbugs.annotations.SuppressWarnings
public SimpleSSLTestServer(final File truststore, final String truststorePass,
final File keystore, final String keystorePass, final boolean clientAuthRequred) throws Exception{
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystore), keystorePass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keystorePass.toCharArray());
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(new FileInputStream(truststore), keystorePass.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
ss = sc.getServerSocketFactory().createServerSocket(0);
((SSLServerSocket) ss).setNeedClientAuth(clientAuthRequred);
}
public void accept() throws Exception{
new Thread(){
@Override
public void run(){
Socket sock = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try{
sock = ss.accept();
reader = new BufferedReader(new InputStreamReader(sock.getInputStream(), Charset.defaultCharset()));
writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), Charset.defaultCharset()));
reader.readLine(); // we really don't care what the client says, he's getting the special regardless...
writer.write(CANNED_RESPONSE);
writer.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
Closeables.close(reader, true);
Closeables.close(writer, true);
sock.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
public void close() throws Exception{
ss.close();
}
public int getPort() {
return ss.getLocalPort();
}
}
| 3,623 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientResponse.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.reflect.TypeToken;
import com.netflix.client.ClientException;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.http.HttpHeaders;
import com.netflix.client.http.HttpResponse;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A NIWS Client Response
* (this version just wraps Jersey Client response)
* @author stonse
*
*/
class HttpClientResponse implements HttpResponse {
private final ClientResponse bcr;
private final Multimap<String, String> headers = ArrayListMultimap.<String, String>create();
private final HttpHeaders httpHeaders;
private final URI requestedURI;
private final IClientConfig overrideConfig;
public HttpClientResponse(ClientResponse cr, URI requestedURI, IClientConfig config){
bcr = cr;
this.requestedURI = requestedURI;
this.overrideConfig = config;
for (Map.Entry<String, List<String>> entry: bcr.getHeaders().entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
headers.putAll(entry.getKey(), entry.getValue());
}
}
httpHeaders = new HttpHeaders() {
@Override
public String getFirstValue(String headerName) {
return bcr.getHeaders().getFirst(headerName);
}
@Override
public List<String> getAllValues(String headerName) {
return bcr.getHeaders().get(headerName);
}
@Override
public List<Entry<String, String>> getAllHeaders() {
MultivaluedMap<String, String> map = bcr.getHeaders();
List<Entry<String, String>> result = Lists.newArrayList();
for (Map.Entry<String, List<String>> header: map.entrySet()) {
String name = header.getKey();
for (String value: header.getValue()) {
result.add(new AbstractMap.SimpleEntry<String, String>(name, value));
}
}
return result;
}
@Override
public boolean containsHeader(String name) {
return bcr.getHeaders().containsKey(name);
}
};
}
/**
* Returns the raw entity if available from the response
* @return
* @throws IllegalArgumentException
*/
public InputStream getRawEntity() {
return bcr.getEntityInputStream();
}
public <T> T getEntity(Class<T> c) throws Exception {
return bcr.getEntity(c);
}
@Override
public Map<String, Collection<String>> getHeaders() {
return headers.asMap();
}
@Override
public int getStatus() {
return bcr.getStatus();
}
@Override
public boolean isSuccess() {
boolean isSuccess = false;
ClientResponse.Status s = bcr != null? bcr.getClientResponseStatus(): null;
isSuccess = s!=null? (s.getFamily() == javax.ws.rs.core.Response.Status.Family.SUCCESSFUL): false;
return isSuccess;
}
@Override
public boolean hasEntity() {
return bcr.hasEntity();
}
@Override
public URI getRequestedURI() {
return requestedURI;
}
@Override
public Object getPayload() throws ClientException {
if (hasEntity()) {
return getRawEntity();
} else {
return null;
}
}
@Override
public boolean hasPayload() {
return hasEntity();
}
public ClientResponse getJerseyClientResponse() {
return bcr;
}
@Override
public void close() {
bcr.close();
}
@Override
public InputStream getInputStream() {
return getRawEntity();
}
@Override
public String getStatusLine() {
return bcr.getClientResponseStatus().toString();
}
@Override
public HttpHeaders getHttpHeaders() {
return httpHeaders;
}
@Override
public <T> T getEntity(TypeToken<T> type) throws Exception {
return bcr.getEntity(new GenericType<T>(type.getType()));
}
@Override
public <T> T getEntity(Type type) throws Exception {
return bcr.getEntity(new GenericType<T>(type));
}
}
| 3,624 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientRequest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import java.net.URI;
import javax.ws.rs.core.MultivaluedMap;
import com.netflix.client.ClientRequest;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.http.HttpRequest;
/**
* @see HttpRequest
* @author awang
*
*/
@Deprecated
public class HttpClientRequest extends ClientRequest {
public enum Verb {
GET("GET"),
PUT("PUT"),
POST("POST"),
DELETE("DELETE"),
OPTIONS("OPTIONS"),
HEAD("HEAD");
private final String verb; // http method
Verb(String verb) {
this.verb = verb;
}
public String verb() {
return verb;
}
}
private MultivaluedMap<String, String> headers;
private MultivaluedMap<String, String> queryParams;
private Object entity;
private Verb verb;
private HttpClientRequest() {
this.verb = Verb.GET;
}
public static class Builder {
private HttpClientRequest request = new HttpClientRequest();
public Builder setUri(URI uri) {
request.setUri(uri);
return this;
}
public Builder setHeaders(MultivaluedMap<String, String> headers) {
request.headers = headers;
return this;
}
public Builder setOverrideConfig(IClientConfig config) {
request.setOverrideConfig(config);
return this;
}
public Builder setRetriable(boolean retriable) {
request.setRetriable(retriable);
return this;
}
public Builder setQueryParams(MultivaluedMap<String, String> queryParams) {
request.queryParams = queryParams;
return this;
}
public Builder setEntity(Object entity) {
request.entity = entity;
return this;
}
public Builder setVerb(Verb verb) {
request.verb = verb;
return this;
}
public Builder setLoadBalancerKey(Object loadBalancerKey) {
request.setLoadBalancerKey(loadBalancerKey);
return this;
}
public HttpClientRequest build() {
return request;
}
}
public MultivaluedMap<String, String> getQueryParams() {
return queryParams;
}
public Verb getVerb() {
return verb;
}
public MultivaluedMap<String, String> getHeaders() {
return headers;
}
public Object getEntity() {
return entity;
}
@Override
public boolean isRetriable() {
if (this.verb == Verb.GET && isRetriable == null) {
return true;
}
return super.isRetriable();
}
public static Builder newBuilder() {
return new Builder();
}
@Override
public HttpClientRequest replaceUri(URI newURI) {
return (new Builder()).setUri(newURI)
.setEntity(this.getEntity())
.setHeaders(this.getHeaders())
.setOverrideConfig(this.getOverrideConfig())
.setQueryParams(this.getQueryParams())
.setRetriable(this.isRetriable())
.setLoadBalancerKey(this.getLoadBalancerKey())
.setVerb(this.getVerb()).build();
}
}
| 3,625 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpPrimeConnection.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.client.IPrimeConnection;
import com.netflix.client.config.IClientConfig;
import com.netflix.http4.NFHttpClient;
import com.netflix.http4.NFHttpClientFactory;
import com.netflix.loadbalancer.Server;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.params.HttpConnectionParams;
/**
* An implementation of {@link IPrimeConnection} using Apache HttpClient.
*
* @author awang
*
*/
public class HttpPrimeConnection implements IPrimeConnection {
private static final Logger logger = LoggerFactory.getLogger(HttpPrimeConnection.class);
private NFHttpClient client;
public HttpPrimeConnection() {
}
@Override
public boolean connect(Server server, String primeConnectionsURIPath) throws Exception {
String url = "http://" + server.getHostPort() + primeConnectionsURIPath;
logger.debug("Trying URL: {}", url);
HttpUriRequest get = new HttpGet(url);
HttpResponse response = null;
try {
response = client.execute(get);
if (logger.isDebugEnabled() && response.getStatusLine() != null) {
logger.debug("Response code:" + response.getStatusLine().getStatusCode());
}
} finally {
get.abort();
}
return true;
}
@Override
public void initWithNiwsConfig(IClientConfig niwsClientConfig) {
client = NFHttpClientFactory.getNamedNFHttpClient(niwsClientConfig.getClientName() + "-PrimeConnsClient", false);
HttpConnectionParams.setConnectionTimeout(client.getParams(), 2000);
}
}
| 3,626 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/HttpClientLoadBalancerErrorHandler.java | package com.netflix.niws.client.http;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.List;
import org.apache.http.ConnectionClosedException;
import org.apache.http.NoHttpResponseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import com.google.common.collect.Lists;
import com.netflix.client.ClientException;
import com.netflix.client.DefaultLoadBalancerRetryHandler;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.http.HttpResponse;
public class HttpClientLoadBalancerErrorHandler extends DefaultLoadBalancerRetryHandler {
@SuppressWarnings("unchecked")
protected List<Class<? extends Throwable>> retriable =
Lists.<Class<? extends Throwable>>newArrayList(ConnectException.class, SocketTimeoutException.class, ConnectTimeoutException.class,
NoHttpResponseException.class, ConnectionPoolTimeoutException.class, ConnectionClosedException.class, HttpHostConnectException.class);
@SuppressWarnings("unchecked")
protected List<Class<? extends Throwable>> circuitRelated =
Lists.<Class<? extends Throwable>>newArrayList(SocketException.class, SocketTimeoutException.class, ConnectTimeoutException.class,
ConnectionClosedException.class, HttpHostConnectException.class);
public HttpClientLoadBalancerErrorHandler() {
super();
}
public HttpClientLoadBalancerErrorHandler(IClientConfig clientConfig) {
super(clientConfig);
}
public HttpClientLoadBalancerErrorHandler(int retrySameServer,
int retryNextServer, boolean retryEnabled) {
super(retrySameServer, retryNextServer, retryEnabled);
}
/**
* @return true if the Throwable has one of the following exception type as a cause:
* {@link SocketException}, {@link SocketTimeoutException}
*/
@Override
public boolean isCircuitTrippingException(Throwable e) {
if (e instanceof ClientException) {
return ((ClientException) e).getErrorType() == ClientException.ErrorType.SERVER_THROTTLED;
}
return super.isCircuitTrippingException(e);
}
@Override
public boolean isRetriableException(Throwable e, boolean sameServer) {
if (e instanceof ClientException) {
ClientException ce = (ClientException) e;
if (ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) {
return !sameServer && retryEnabled;
}
}
return super.isRetriableException(e, sameServer);
}
@Override
protected List<Class<? extends Throwable>> getRetriableExceptions() {
return retriable;
}
@Override
protected List<Class<? extends Throwable>> getCircuitRelatedExceptions() {
return circuitRelated;
}
}
| 3,627 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/niws/client/http/RestClient.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.niws.client.http;
import java.io.File;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import com.netflix.client.config.Property;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientException;
import com.netflix.client.ClientFactory;
import com.netflix.client.RequestSpecificRetryHandler;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.client.ssl.AbstractSslContextFactory;
import com.netflix.client.ssl.ClientSslSocketFactoryException;
import com.netflix.client.ssl.URLSslContextFactory;
import com.netflix.http4.NFHttpClient;
import com.netflix.http4.NFHttpClientFactory;
import com.netflix.http4.NFHttpMethodRetryHandler;
import com.netflix.http4.ssl.KeyStoreAwareSocketFactory;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.util.Pair;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.ApacheHttpClient4Handler;
import com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;
import com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;
/**
* A client that is essentially a wrapper around Jersey client. By default, it uses HttpClient for underlying HTTP communication.
* Application can set its own Jersey client with this class, but doing so will void all client configurations set in {@link IClientConfig}.
*
* @deprecated Please see ribbon-rxnetty module for the Netty based client.
*
* @author awang
*
*/
@Deprecated
public class RestClient extends AbstractLoadBalancerAwareClient<HttpRequest, HttpResponse> {
private static IClientConfigKey<Integer> CONN_IDLE_EVICT_TIME_MILLIS = new CommonClientConfigKey<Integer>(
"%s.nfhttpclient.connIdleEvictTimeMilliSeconds") {};
private Client restClient;
private HttpClient httpClient4;
private IClientConfig ncc;
private String restClientName;
private boolean enableConnectionPoolCleanerTask = false;
private Property<Integer> connIdleEvictTimeMilliSeconds;
private int connectionCleanerRepeatInterval;
private int maxConnectionsperHost;
private int maxTotalConnections;
private int connectionTimeout;
private int readTimeout;
private String proxyHost;
private int proxyPort;
private boolean isSecure;
private boolean isHostnameValidationRequired;
private boolean isClientAuthRequired;
private boolean ignoreUserToken;
private ApacheHttpClient4Config config;
boolean bFollowRedirects = CommonClientConfigKey.FollowRedirects.defaultValue();
private static final Logger logger = LoggerFactory.getLogger(RestClient.class);
public RestClient() {
super(null);
}
public RestClient(ILoadBalancer lb) {
super(lb);
restClientName = "default";
}
public RestClient(ILoadBalancer lb, IClientConfig ncc) {
super(lb, ncc);
initWithNiwsConfig(ncc);
}
public RestClient(IClientConfig ncc) {
super(null, ncc);
initWithNiwsConfig(ncc);
}
public RestClient(ILoadBalancer lb, Client jerseyClient) {
super(lb);
this.restClient = jerseyClient;
this.setRetryHandler(new HttpClientLoadBalancerErrorHandler());
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
super.initWithNiwsConfig(clientConfig);
this.ncc = clientConfig;
this.restClientName = ncc.getClientName();
this.isSecure = ncc.get(CommonClientConfigKey.IsSecure, this.isSecure);
this.isHostnameValidationRequired = ncc.get(CommonClientConfigKey.IsHostnameValidationRequired, this.isHostnameValidationRequired);
this.isClientAuthRequired = ncc.get(CommonClientConfigKey.IsClientAuthRequired, this.isClientAuthRequired);
this.bFollowRedirects = ncc.get(CommonClientConfigKey.FollowRedirects, true);
this.ignoreUserToken = ncc.get(CommonClientConfigKey.IgnoreUserTokenInConnectionPoolForSecureClient, this.ignoreUserToken);
this.config = new DefaultApacheHttpClient4Config();
this.config.getProperties().put(
ApacheHttpClient4Config.PROPERTY_CONNECT_TIMEOUT,
ncc.get(CommonClientConfigKey.ConnectTimeout));
this.config.getProperties().put(
ApacheHttpClient4Config.PROPERTY_READ_TIMEOUT,
ncc.get(CommonClientConfigKey.ReadTimeout));
this.restClient = apacheHttpClientSpecificInitialization();
this.setRetryHandler(new HttpClientLoadBalancerErrorHandler(ncc));
}
private void throwInvalidValue(IClientConfigKey<?> key, Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + key, e);
}
protected Client apacheHttpClientSpecificInitialization() {
httpClient4 = NFHttpClientFactory.getNamedNFHttpClient(restClientName, this.ncc, true);
if (httpClient4 instanceof AbstractHttpClient) {
// DONT use our NFHttpClient's default Retry Handler since we have
// retry handling (same server/next server) in RestClient itself
((AbstractHttpClient) httpClient4).setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(restClientName, 0, false, 0));
} else {
logger.warn("Unexpected error: Unable to disable NFHttpClient "
+ "retry handler, this most likely will not cause an "
+ "issue but probably should be looked at");
}
HttpParams httpClientParams = httpClient4.getParams();
// initialize Connection Manager cleanup facility
NFHttpClient nfHttpClient = (NFHttpClient) httpClient4;
// should we enable connection cleanup for idle connections?
try {
enableConnectionPoolCleanerTask = ncc.getOrDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled);
nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
}
if (enableConnectionPoolCleanerTask) {
try {
connectionCleanerRepeatInterval = ncc.getOrDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval);
nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
}
try {
connIdleEvictTimeMilliSeconds = ncc.getDynamicProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds);
nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
}
nfHttpClient.initConnectionCleanerTask();
}
try {
maxConnectionsperHost = ncc.getOrDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost);
ClientConnectionManager connMgr = httpClient4.getConnectionManager();
if (connMgr instanceof ThreadSafeClientConnManager) {
((ThreadSafeClientConnManager) connMgr)
.setDefaultMaxPerRoute(maxConnectionsperHost);
}
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
}
try {
maxTotalConnections = ncc.getOrDefault(CommonClientConfigKey.MaxTotalHttpConnections);
ClientConnectionManager connMgr = httpClient4.getConnectionManager();
if (connMgr instanceof ThreadSafeClientConnManager) {
((ThreadSafeClientConnManager) connMgr)
.setMaxTotal(maxTotalConnections);
}
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.MaxTotalHttpConnections, e1);
}
try {
connectionTimeout = ncc.getOrDefault(CommonClientConfigKey.ConnectTimeout);
HttpConnectionParams.setConnectionTimeout(httpClientParams,
connectionTimeout);
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.ConnectTimeout, e1);
}
try {
readTimeout = ncc.getOrDefault(CommonClientConfigKey.ReadTimeout);
HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
} catch (Exception e1) {
throwInvalidValue(CommonClientConfigKey.ReadTimeout, e1);
}
// httpclient 4 seems to only have one buffer size controlling both
// send/receive - so let's take the bigger of the two values and use
// it as buffer size
int bufferSize = Integer.MIN_VALUE;
if (ncc.get(CommonClientConfigKey.ReceiveBufferSize) != null) {
try {
bufferSize = ncc.getOrDefault(CommonClientConfigKey.ReceiveBufferSize);
} catch (Exception e) {
throwInvalidValue(CommonClientConfigKey.ReceiveBufferSize, e);
}
if (ncc.get(CommonClientConfigKey.SendBufferSize) != null) {
try {
int sendBufferSize = ncc.getOrDefault(CommonClientConfigKey.SendBufferSize);
if (sendBufferSize > bufferSize) {
bufferSize = sendBufferSize;
}
} catch (Exception e) {
throwInvalidValue(CommonClientConfigKey.SendBufferSize,e);
}
}
}
if (bufferSize != Integer.MIN_VALUE) {
HttpConnectionParams.setSocketBufferSize(httpClientParams,
bufferSize);
}
if (ncc.get(CommonClientConfigKey.StaleCheckingEnabled) != null) {
try {
HttpConnectionParams.setStaleCheckingEnabled(
httpClientParams, ncc.getOrDefault(CommonClientConfigKey.StaleCheckingEnabled));
} catch (Exception e) {
throwInvalidValue(CommonClientConfigKey.StaleCheckingEnabled, e);
}
}
if (ncc.get(CommonClientConfigKey.Linger) != null) {
try {
HttpConnectionParams.setLinger(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.Linger));
} catch (Exception e) {
throwInvalidValue(CommonClientConfigKey.Linger, e);
}
}
if (ncc.get(CommonClientConfigKey.ProxyHost) != null) {
try {
proxyHost = (String) ncc.getOrDefault(CommonClientConfigKey.ProxyHost);
proxyPort = ncc.getOrDefault(CommonClientConfigKey.ProxyPort);
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpClient4.getParams()
.setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
} catch (Exception e) {
throwInvalidValue(CommonClientConfigKey.ProxyHost, e);
}
}
if (isSecure) {
final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
final ClientConnectionManager currentManager = httpClient4.getConnectionManager();
AbstractSslContextFactory abstractFactory = null;
if ( // if client auth is required, need both a truststore and a keystore to warrant configuring
// if client is not is not required, we only need a keystore OR a truststore to warrant configuring
(isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null))
|| (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))
) {
try {
abstractFactory = new URLSslContextFactory(trustStoreUrl,
ncc.get(CommonClientConfigKey.TrustStorePassword),
keyStoreUrl,
ncc.get(CommonClientConfigKey.KeyStorePassword));
} catch (ClientSslSocketFactoryException e) {
throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
}
}
KeyStoreAwareSocketFactory awareSocketFactory;
try {
awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractFactory) :
new KeyStoreAwareSocketFactory(abstractFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
currentManager.getSchemeRegistry().register(new Scheme(
"https",443, awareSocketFactory));
} catch (Exception e) {
throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
}
}
// Warning that if user tokens are used (i.e. ignoreUserToken == false) this may be prevent SSL connections from being
// reused, which is generally not the intent for long-living proxy connections and the like.
// See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html
if (ignoreUserToken) {
((DefaultHttpClient) httpClient4).setUserTokenHandler(new UserTokenHandler() {
@Override
public Object getUserToken(HttpContext context) {
return null;
}
});
}
// custom SSL Factory handler
String customSSLFactoryClassName = ncc.get(CommonClientConfigKey.CustomSSLSocketFactoryClassName);
if (customSSLFactoryClassName != null){
try{
SSLSocketFactory customSocketFactory = (SSLSocketFactory) ClientFactory.instantiateInstanceWithClientConfig(customSSLFactoryClassName, ncc);
httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme(
"https",443, customSocketFactory));
} catch(Exception e){
throwInvalidValue(CommonClientConfigKey.CustomSSLSocketFactoryClassName, e);
}
}
ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpClient4, new BasicCookieStore(), false);
return new ApacheHttpClient4(handler, config);
}
public void resetSSLSocketFactory(AbstractSslContextFactory abstractContextFactory){
try {
KeyStoreAwareSocketFactory awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractContextFactory) :
new KeyStoreAwareSocketFactory(abstractContextFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme(
"https",443, awareSocketFactory));
} catch (Exception e) {
throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
}
}
public KeyStore getKeyStore(){
SchemeRegistry registry = httpClient4.getConnectionManager().getSchemeRegistry();
if(! registry.getSchemeNames().contains("https")){
throw new IllegalStateException("Registry does not include an 'https' entry.");
}
SchemeSocketFactory awareSocketFactory = httpClient4.getConnectionManager().getSchemeRegistry().getScheme("https").getSchemeSocketFactory();
if(awareSocketFactory instanceof KeyStoreAwareSocketFactory){
return ((KeyStoreAwareSocketFactory) awareSocketFactory).getKeyStore();
}else{
throw new IllegalStateException("Cannot extract keystore from scheme socket factory of type: " + awareSocketFactory.getClass().getName());
}
}
public static URL getResource(String resourceName)
{
URL url = null;
// attempt to load from the context classpath
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader != null) {
url = loader.getResource(resourceName);
}
if (url == null) {
// attempt to load from the system classpath
url = ClassLoader.getSystemResource(resourceName);
}
if (url == null) {
// attempt to load from the system classpath
url = RestClient.class.getResource(resourceName);
}
if (url == null) {
// attempt to load from the system classpath
url = RestClient.class.getClassLoader().getResource(resourceName);
}
if (url == null) {
try {
resourceName = URLDecoder.decode(resourceName, "UTF-8");
url = (new File(resourceName)).toURI().toURL();
} catch (Exception e) {
logger.error("Problem loading resource", e);
}
}
return url;
}
public Client getJerseyClient() {
return restClient;
}
public void setJerseyClient(Client c) {
restClient = c;
}
private URL getResourceForOptionalProperty(final IClientConfigKey configKey) {
final String propValue = (String) ncc.get(configKey);
URL result = null;
if (propValue != null) {
result = getResource(propValue);
if (result == null) {
throw new IllegalArgumentException("No resource found for " + configKey + ": "
+ propValue);
}
}
return result;
}
public HttpResponse execute(HttpRequest task) throws Exception {
return execute(task, null);
}
@Override
public HttpResponse execute(HttpRequest task, IClientConfig requestConfig) throws Exception {
IClientConfig config = (requestConfig == null) ? task.getOverrideConfig() : requestConfig;
return execute(task.getVerb(), task.getUri(),
task.getHeaders(), task.getQueryParams(), config, task.getEntity());
}
@Override
protected int getDefaultPortFromScheme(String scheme) {
int port = super.getDefaultPortFromScheme(scheme);
if (port < 0) {
return 80;
} else {
return port;
}
}
@Override
protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(URI uri) {
boolean isSecure = ncc.get(CommonClientConfigKey.IsSecure, this.isSecure);
String scheme = uri.getScheme();
if (scheme != null) {
isSecure = scheme.equalsIgnoreCase("https");
}
int port = uri.getPort();
if (port < 0 && !isSecure){
port = 80;
} else if (port < 0 && isSecure){
port = 443;
}
if (scheme == null){
if (isSecure) {
scheme = "https";
} else {
scheme = "http";
}
}
return new Pair<>(scheme, port);
}
private HttpResponse execute(HttpRequest.Verb verb, URI uri,
Map<String, Collection<String>> headers, Map<String, Collection<String>> params,
IClientConfig overriddenClientConfig, Object requestEntity) throws Exception {
HttpClientResponse thisResponse = null;
final boolean bbFollowRedirects = Optional.ofNullable(overriddenClientConfig)
.flatMap(config -> config.getIfSet(CommonClientConfigKey.FollowRedirects))
.orElse(bFollowRedirects);
restClient.setFollowRedirects(bbFollowRedirects);
if (logger.isDebugEnabled()) {
logger.debug("RestClient sending new Request(" + verb
+ ": ) " + uri);
}
WebResource xResource = restClient.resource(uri.toString());
if (params != null) {
for (Map.Entry<String, Collection<String>> entry: params.entrySet()) {
String name = entry.getKey();
for (String value: entry.getValue()) {
xResource = xResource.queryParam(name, value);
}
}
}
ClientResponse jerseyResponse;
Builder b = xResource.getRequestBuilder();
if (headers != null) {
for (Map.Entry<String, Collection<String>> entry: headers.entrySet()) {
String name = entry.getKey();
for (String value: entry.getValue()) {
b = b.header(name, value);
}
}
}
Object entity = requestEntity;
switch (verb) {
case GET:
jerseyResponse = b.get(ClientResponse.class);
break;
case POST:
jerseyResponse = b.post(ClientResponse.class, entity);
break;
case PUT:
jerseyResponse = b.put(ClientResponse.class, entity);
break;
case DELETE:
jerseyResponse = b.delete(ClientResponse.class);
break;
case HEAD:
jerseyResponse = b.head();
break;
case OPTIONS:
jerseyResponse = b.options(ClientResponse.class);
break;
default:
throw new ClientException(
ClientException.ErrorType.GENERAL,
"You have to one of the REST verbs such as GET, POST etc.");
}
thisResponse = new HttpClientResponse(jerseyResponse, uri, overriddenClientConfig);
if (thisResponse.getStatus() == 503){
thisResponse.close();
throw new ClientException(ClientException.ErrorType.SERVER_THROTTLED);
}
return thisResponse;
}
@Override
protected boolean isRetriableException(Throwable e) {
if (e instanceof ClientException
&& ((ClientException)e).getErrorType() == ClientException.ErrorType.SERVER_THROTTLED){
return false;
}
boolean shouldRetry = isConnectException(e) || isSocketException(e);
return shouldRetry;
}
@Override
protected boolean isCircuitBreakerException(Throwable e) {
if (e instanceof ClientException) {
ClientException clientException = (ClientException) e;
if (clientException.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) {
return true;
}
}
return isConnectException(e) || isSocketException(e);
}
private static boolean isSocketException(Throwable e) {
int levelCount = 0;
while (e != null && levelCount < 10) {
if ((e instanceof SocketException) || (e instanceof SocketTimeoutException)) {
return true;
}
e = e.getCause();
levelCount++;
}
return false;
}
private static boolean isConnectException(Throwable e) {
int levelCount = 0;
while (e != null && levelCount < 10) {
if ((e instanceof SocketException)
|| ((e instanceof org.apache.http.conn.ConnectTimeoutException)
&& !(e instanceof org.apache.http.conn.ConnectionPoolTimeoutException))) {
return true;
}
e = e.getCause();
levelCount++;
}
return false;
}
@Override
protected Pair<String, Integer> deriveHostAndPortFromVipAddress(String vipAddress)
throws URISyntaxException, ClientException {
if (!vipAddress.contains("http")) {
vipAddress = "http://" + vipAddress;
}
return super.deriveHostAndPortFromVipAddress(vipAddress);
}
@Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
HttpRequest request, IClientConfig requestConfig) {
if (!request.isRetriable()) {
return new RequestSpecificRetryHandler(false, false, this.getRetryHandler(), requestConfig);
}
if (this.ncc.get(CommonClientConfigKey.OkToRetryOnAllOperations, false)) {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), requestConfig);
}
if (request.getVerb() != HttpRequest.Verb.GET) {
return new RequestSpecificRetryHandler(true, false, this.getRetryHandler(), requestConfig);
} else {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), requestConfig);
}
}
public void shutdown() {
ILoadBalancer lb = this.getLoadBalancer();
if (lb instanceof BaseLoadBalancer) {
((BaseLoadBalancer) lb).shutdown();
}
NFHttpClientFactory.shutdownNFHttpClient(restClientName);
}
}
| 3,628 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/loadbalancer/PingUrl.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.loadbalancer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Ping implementation if you want to do a "health check" kind of Ping. This
* will be a "real" ping. As in a real http/s call is made to this url e.g.
* http://ec2-75-101-231-85.compute-1.amazonaws.com:7101/cs/hostRunning
*
* Some services/clients choose PingDiscovery - which is quick but is not a real
* ping. i.e It just asks discovery (eureka) in-memory cache if the server is present
* in its Roster PingUrl on the other hand, makes an actual call. This is more
* expensive - but its the "standard" way most VIPs and other services perform
* HealthChecks.
*
* Choose your Ping based on your needs.
*
* @author stonse
*
*/
public class PingUrl implements IPing {
private static final Logger LOGGER = LoggerFactory.getLogger(PingUrl.class);
String pingAppendString = "";
boolean isSecure = false;
String expectedContent = null;
/*
*
* Send one ping only.
*
* Well, send what you need to determine whether or not the
* server is still alive. Should return within a "reasonable"
* time.
*/
public PingUrl() {
}
public PingUrl(boolean isSecure, String pingAppendString) {
this.isSecure = isSecure;
this.pingAppendString = (pingAppendString != null) ? pingAppendString : "";
}
public void setPingAppendString(String pingAppendString) {
this.pingAppendString = (pingAppendString != null) ? pingAppendString : "";
}
public String getPingAppendString() {
return pingAppendString;
}
public boolean isSecure() {
return isSecure;
}
/**
* Should the Secure protocol be used to Ping
* @param isSecure
*/
public void setSecure(boolean isSecure) {
this.isSecure = isSecure;
}
public String getExpectedContent() {
return expectedContent;
}
/**
* Is there a particular content you are hoping to see?
* If so -set this here.
* for e.g. the WCS server sets the content body to be 'true'
* Please be advised that this content should match the actual
* content exactly for this to work. Else yo may get false status.
* @param expectedContent
*/
public void setExpectedContent(String expectedContent) {
this.expectedContent = expectedContent;
}
public boolean isAlive(Server server) {
String urlStr = "";
if (isSecure){
urlStr = "https://";
}else{
urlStr = "http://";
}
urlStr += server.getId();
urlStr += getPingAppendString();
boolean isAlive = false;
HttpClient httpClient = new DefaultHttpClient();
HttpUriRequest getRequest = new HttpGet(urlStr);
String content=null;
try {
HttpResponse response = httpClient.execute(getRequest);
content = EntityUtils.toString(response.getEntity());
isAlive = (response.getStatusLine().getStatusCode() == 200);
if (getExpectedContent()!=null){
LOGGER.debug("content:" + content);
if (content == null){
isAlive = false;
}else{
if (content.equals(getExpectedContent())){
isAlive = true;
}else{
isAlive = false;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
// Release the connection.
getRequest.abort();
}
return isAlive;
}
public static void main(String[] args){
PingUrl p = new PingUrl(false,"/cs/hostRunning");
p.setExpectedContent("true");
Server s = new Server("ec2-75-101-231-85.compute-1.amazonaws.com", 7101);
boolean isAlive = p.isAlive(s);
System.out.println("isAlive:" + isAlive);
}
}
| 3,629 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/MonitoredConnectionManager.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.tsccm.AbstractConnPool;
import org.apache.http.impl.conn.tsccm.ConnPoolByRoute;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import com.google.common.annotations.VisibleForTesting;
/**
* A connection manager that uses {@link NamedConnectionPool}, which provides
* connection reuse statistics, as its underlying connection pool.
*
* @author awang
*
*/
public class MonitoredConnectionManager extends ThreadSafeClientConnManager {
public MonitoredConnectionManager(String name) {
super();
initMonitors(name);
}
public MonitoredConnectionManager(String name, SchemeRegistry schreg, long connTTL,
TimeUnit connTTLTimeUnit) {
super(schreg, connTTL, connTTLTimeUnit);
initMonitors(name);
}
public MonitoredConnectionManager(String name, SchemeRegistry schreg) {
super(schreg);
initMonitors(name);
}
void initMonitors(String name) {
if (this.pool instanceof NamedConnectionPool) {
((NamedConnectionPool) this.pool).initMonitors(name);
}
}
@Override
@Deprecated
protected AbstractConnPool createConnectionPool(HttpParams params) {
return new NamedConnectionPool(connOperator, params);
}
@Override
protected ConnPoolByRoute createConnectionPool(long connTTL,
TimeUnit connTTLTimeUnit) {
return new NamedConnectionPool(connOperator, connPerRoute, 20, connTTL, connTTLTimeUnit);
}
@VisibleForTesting
ConnPoolByRoute getConnectionPool() {
return this.pool;
}
@Override
public ClientConnectionRequest requestConnection(HttpRoute route,
Object state) {
// TODO Auto-generated method stub
return super.requestConnection(route, state);
}
}
| 3,630 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpMethodRetryHandler.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
/**
* A simple netflix specific extension class for {@link org.apache.commons.httpclient.DefaultHttpMethodRetryHandler}.
*
* Provides a configurable override for the number of retries. Also waits for a configurable time before retry.
*/
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.servo.monitor.DynamicCounter;
public class NFHttpMethodRetryHandler extends DefaultHttpRequestRetryHandler {
private static final String RETRY_COUNTER = "PLATFORM:NFttpClient:Retries:";
private Logger logger = LoggerFactory.getLogger(NFHttpMethodRetryHandler.class);
private int sleepTimeFactorMs;
private String httpClientName;
/**
* Creates a new NFHttpMethodRetryHandler.
* @param httpClientName - the name of the nfhttpclient
* @param retryCount the number of times a method will be retried
* @param requestSentRetryEnabled if true, methods that have successfully sent their request will be retried
* @param sleepTimeFactorMs number of milliseconds to sleep before the next try. This factor is used along with execution count
* to determine the sleep time (ie) executionCount * sleepTimeFactorMs
*/
public NFHttpMethodRetryHandler(String httpClientName, int retryCount, boolean requestSentRetryEnabled, int sleepTimeFactorMs) {
super(retryCount, requestSentRetryEnabled);
this.httpClientName = httpClientName;
this.sleepTimeFactorMs = sleepTimeFactorMs;
}
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG")
public boolean retryRequest(
final IOException exception,
int executionCount,
HttpContext context
) {
if (super.retryRequest(exception, executionCount, context)) {
HttpRequest request = (HttpRequest)
context.getAttribute(ExecutionContext.HTTP_REQUEST);
String methodName = request.getRequestLine().getMethod();
String path = "UNKNOWN_PATH";
if(request instanceof HttpUriRequest) {
HttpUriRequest uriReq = (HttpUriRequest) request;
path = uriReq.getURI().toString();
}
try {
Thread.sleep(executionCount * this.sleepTimeFactorMs);
}
catch (InterruptedException e) {
logger.warn("Interrupted while sleep before retrying http method " + methodName + " " + path, e);
}
DynamicCounter.increment(RETRY_COUNTER + methodName + ":" + path);
return true;
}
return false;
}
}
| 3,631 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/NamedConnectionPool.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.tsccm.BasicPoolEntry;
import org.apache.http.impl.conn.tsccm.ConnPoolByRoute;
import org.apache.http.impl.conn.tsccm.PoolEntryRequest;
import org.apache.http.impl.conn.tsccm.RouteSpecificPool;
import org.apache.http.impl.conn.tsccm.WaitingThreadAborter;
import org.apache.http.params.HttpParams;
import com.google.common.base.Preconditions;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.monitor.Timer;
/**
* A connection pool that provides Servo counters to monitor the efficiency.
* Three counters are provided: counter for getting free entries (or reusing entries),
* counter for creating new entries, and counter for every connection request.
*
* @author awang
*
*/
public class NamedConnectionPool extends ConnPoolByRoute {
private Counter freeEntryCounter;
private Counter createEntryCounter;
private Counter requestCounter;
private Counter releaseCounter;
private Counter deleteCounter;
private Timer requestTimer;
private Timer creationTimer;
private String name;
public NamedConnectionPool(String name, ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections, long connTTL,
TimeUnit connTTLTimeUnit) {
super(operator, connPerRoute, maxTotalConnections, connTTL, connTTLTimeUnit);
initMonitors(name);
}
public NamedConnectionPool(String name, ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections) {
super(operator, connPerRoute, maxTotalConnections);
initMonitors(name);
}
public NamedConnectionPool(String name, ClientConnectionOperator operator,
HttpParams params) {
super(operator, params);
initMonitors(name);
}
NamedConnectionPool(ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections, long connTTL,
TimeUnit connTTLTimeUnit) {
super(operator, connPerRoute, maxTotalConnections, connTTL, connTTLTimeUnit);
}
NamedConnectionPool(ClientConnectionOperator operator,
ConnPerRoute connPerRoute, int maxTotalConnections) {
super(operator, connPerRoute, maxTotalConnections);
}
NamedConnectionPool(ClientConnectionOperator operator,
HttpParams params) {
super(operator, params);
}
void initMonitors(String name) {
Preconditions.checkNotNull(name);
freeEntryCounter = Monitors.newCounter(name + "_Reuse");
createEntryCounter = Monitors.newCounter(name + "_CreateNew");
requestCounter = Monitors.newCounter(name + "_Request");
releaseCounter = Monitors.newCounter(name + "_Release");
deleteCounter = Monitors.newCounter(name + "_Delete");
requestTimer = Monitors.newTimer(name + "_RequestConnectionTimer", TimeUnit.MILLISECONDS);
creationTimer = Monitors.newTimer(name + "_CreateConnectionTimer", TimeUnit.MILLISECONDS);
this.name = name;
Monitors.registerObject(name, this);
}
@Override
public PoolEntryRequest requestPoolEntry(HttpRoute route, Object state) {
requestCounter.increment();
return super.requestPoolEntry(route, state);
}
@Override
protected BasicPoolEntry getFreeEntry(RouteSpecificPool rospl, Object state) {
BasicPoolEntry entry = super.getFreeEntry(rospl, state);
if (entry != null) {
freeEntryCounter.increment();
}
return entry;
}
@Override
protected BasicPoolEntry createEntry(RouteSpecificPool rospl,
ClientConnectionOperator op) {
createEntryCounter.increment();
Stopwatch stopWatch = creationTimer.start();
try {
return super.createEntry(rospl, op);
} finally {
stopWatch.stop();
}
}
@Override
protected BasicPoolEntry getEntryBlocking(HttpRoute route, Object state,
long timeout, TimeUnit tunit, WaitingThreadAborter aborter)
throws ConnectionPoolTimeoutException, InterruptedException {
Stopwatch stopWatch = requestTimer.start();
try {
return super.getEntryBlocking(route, state, timeout, tunit, aborter);
} finally {
stopWatch.stop();
}
}
@Override
public void freeEntry(BasicPoolEntry entry, boolean reusable,
long validDuration, TimeUnit timeUnit) {
releaseCounter.increment();
super.freeEntry(entry, reusable, validDuration, timeUnit);
}
@Override
protected void deleteEntry(BasicPoolEntry entry) {
deleteCounter.increment();
super.deleteEntry(entry);
}
public final long getFreeEntryCount() {
return freeEntryCounter.getValue().longValue();
}
public final long getCreatedEntryCount() {
return createEntryCounter.getValue().longValue();
}
public final long getRequestsCount() {
return requestCounter.getValue().longValue();
}
public final long getReleaseCount() {
return releaseCounter.getValue().longValue();
}
public final long getDeleteCount() {
return deleteCounter.getValue().longValue();
}
@Monitor(name="connectionCount", type=DataSourceType.GAUGE)
public int getConnectionCount() {
return this.getConnectionsInPool();
}
@Override
public void shutdown() {
super.shutdown();
Monitors.unregisterObject(name, this);
}
}
| 3,632 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClientFactory.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.client.config.ClientConfigFactory;
import org.apache.commons.collections.keyvalue.MultiKey;
import com.netflix.client.config.IClientConfig;
import com.netflix.servo.monitor.Monitors;
/**
* Factory class to get an instance of NFHttpClient
* @author stonse
*
*/
public class NFHttpClientFactory {
private static Map<MultiKey,NFHttpClient> clientMap = new ConcurrentHashMap<MultiKey,NFHttpClient>();
private static Map<String,NFHttpClient> namedClientMap = new ConcurrentHashMap<String,NFHttpClient>();
private static NFHttpClient defaultClient = new NFHttpClient();
private static Object lock = new Object();
public static NFHttpClient getNFHttpClient(String host, int port){
MultiKey mk = new MultiKey(host,port);
NFHttpClient client = clientMap.get(mk);
if (client == null){
client = new NFHttpClient(host, port);
clientMap.put(mk,client);
}
return client;
}
public static NFHttpClient getNamedNFHttpClient(String name) {
IClientConfig config = ClientConfigFactory.DEFAULT.newConfig();
config.loadProperties(name);
return getNamedNFHttpClient(name, config, true);
}
public static NFHttpClient getNamedNFHttpClient(String name, IClientConfig config) {
return getNamedNFHttpClient(name, config, true);
}
public static NFHttpClient getNamedNFHttpClient(String name, boolean registerMonitor) {
IClientConfig config = ClientConfigFactory.DEFAULT.newConfig();
config.loadProperties(name);
return getNamedNFHttpClient(name, config, registerMonitor);
}
public static NFHttpClient getNamedNFHttpClient(String name, IClientConfig config, boolean registerMonitor) {
NFHttpClient client = namedClientMap.get(name);
//avoid creating multiple HttpClient instances
if (client == null){
synchronized (lock) {
client = namedClientMap.get(name);
if (client == null){
client = new NFHttpClient(name, config, registerMonitor);
namedClientMap.put(name,client);
}
}
}
return client;
}
public static NFHttpClient getDefaultClient() {
return defaultClient;
}
public static void setDefaultClient(NFHttpClient defaultClient) {
NFHttpClientFactory.defaultClient = defaultClient;
}
public static void shutdownNFHttpClient(String name) {
NFHttpClient c = namedClientMap.get(name);
if (c != null) {
c.shutdown();
namedClientMap.remove(name);
Monitors.unregisterObject(name, c);
}
}
}
| 3,633 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/ConnectionPoolCleaner.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import com.netflix.client.config.Property;
import org.apache.http.conn.ClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Class that is responsible to cleanup connections based on a policy
* For e.g. evict all connections from the pool that have been idle for more than x msecs
* @author stonse
*
*/
public class ConnectionPoolCleaner {
private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolCleaner.class);
String name = "default";
ClientConnectionManager connMgr;
ScheduledExecutorService scheduler;
private Property<Integer> connIdleEvictTimeMilliSeconds = Property.of(30*1000);
volatile boolean enableConnectionPoolCleanerTask = false;
long connectionCleanerTimerDelay = 10;
long connectionCleanerRepeatInterval = 30*1000;
private volatile ScheduledFuture<?> scheduledFuture;
public ConnectionPoolCleaner(String name, ClientConnectionManager connMgr, ScheduledExecutorService scheduler){
this.name = name;
this.connMgr = connMgr;
this.scheduler = scheduler;
}
public Property<Integer> getConnIdleEvictTimeMilliSeconds() {
return connIdleEvictTimeMilliSeconds;
}
public void setConnIdleEvictTimeMilliSeconds(Property<Integer> connIdleEvictTimeMilliSeconds) {
this.connIdleEvictTimeMilliSeconds = connIdleEvictTimeMilliSeconds;
}
public boolean isEnableConnectionPoolCleanerTask() {
return enableConnectionPoolCleanerTask;
}
public void setEnableConnectionPoolCleanerTask(
boolean enableConnectionPoolCleanerTask) {
this.enableConnectionPoolCleanerTask = enableConnectionPoolCleanerTask;
}
public long getConnectionCleanerTimerDelay() {
return connectionCleanerTimerDelay;
}
public void setConnectionCleanerTimerDelay(long connectionCleanerTimerDelay) {
this.connectionCleanerTimerDelay = connectionCleanerTimerDelay;
}
public long getConnectionCleanerRepeatInterval() {
return connectionCleanerRepeatInterval;
}
public void setConnectionCleanerRepeatInterval(
long connectionCleanerRepeatInterval) {
this.connectionCleanerRepeatInterval = connectionCleanerRepeatInterval;
}
public void initTask(){
if (enableConnectionPoolCleanerTask) {
scheduledFuture = scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
if (enableConnectionPoolCleanerTask) {
logger.debug("Connection pool clean up started for client {}", name);
cleanupConnections();
} else if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
} catch (Throwable e) {
logger.error("Exception in ConnectionPoolCleanerThread",e);
}
}
}, connectionCleanerTimerDelay, connectionCleanerRepeatInterval, TimeUnit.MILLISECONDS);
logger.info("Initializing ConnectionPoolCleaner for NFHttpClient:" + name);
}
}
void cleanupConnections(){
connMgr.closeExpiredConnections();
connMgr.closeIdleConnections(connIdleEvictTimeMilliSeconds.getOrDefault(), TimeUnit.MILLISECONDS);
}
public void shutdown() {
enableConnectionPoolCleanerTask = false;
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("ConnectionPoolCleaner:" + name);
sb.append(", connIdleEvictTimeMilliSeconds:" + connIdleEvictTimeMilliSeconds.get());
sb.append(", connectionCleanerTimerDelay:" + connectionCleanerTimerDelay);
sb.append(", connectionCleanerRepeatInterval:" + connectionCleanerRepeatInterval);
return sb.toString();
}
}
| 3,634 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/NFHttpClient.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.client.config.ClientConfigFactory;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.IClientConfig;
import com.netflix.client.config.IClientConfigKey;
import com.netflix.client.config.Property;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.monitor.Timer;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Netflix extension of Apache 4.0 HttpClient
* Just so we can wrap around some features.
*
* @author stonse
*
*/
public class NFHttpClient extends DefaultHttpClient {
private static final Logger LOGGER = LoggerFactory.getLogger(NFHttpClient.class);
private static IClientConfigKey<Integer> RETRIES = new CommonClientConfigKey<Integer>("%s.nfhttpclient.retries", 3) {};
private static IClientConfigKey<Integer> SLEEP_TIME_FACTOR_MS = new CommonClientConfigKey<Integer>("%s.nfhttpclient.sleepTimeFactorMs", 10) {};
private static IClientConfigKey<Integer> CONN_IDLE_EVICT_TIME_MILLIS = new CommonClientConfigKey<Integer>("%s.nfhttpclient.connIdleEvictTimeMilliSeconds", 30*1000) {};
protected static final String EXECUTE_TRACER = "HttpClient-ExecuteTimer";
private static ScheduledExecutorService connectionPoolCleanUpScheduler;
private HttpHost httpHost = null;
private HttpRoute httpRoute = null;
private static AtomicInteger numNonNamedHttpClients = new AtomicInteger();
private final String name;
ConnectionPoolCleaner connPoolCleaner;
Property<Integer> connIdleEvictTimeMilliSeconds;
private Property<Integer> retriesProperty;
private Property<Integer> sleepTimeFactorMsProperty;
private Timer tracer;
private Property<Integer> maxTotalConnectionProperty;
private Property<Integer> maxConnectionPerHostProperty;
static {
ThreadFactory factory = (new ThreadFactoryBuilder()).setDaemon(true)
.setNameFormat("Connection pool clean up thread")
.build();
connectionPoolCleanUpScheduler = Executors.newScheduledThreadPool(2, factory);
}
protected NFHttpClient(String host, int port){
super(new ThreadSafeClientConnManager());
this.name = "UNNAMED_" + numNonNamedHttpClients.incrementAndGet();
httpHost = new HttpHost(host, port);
httpRoute = new HttpRoute(httpHost);
init(createDefaultConfig(), false);
}
protected NFHttpClient(){
super(new ThreadSafeClientConnManager());
this.name = "UNNAMED_" + numNonNamedHttpClients.incrementAndGet();
init(createDefaultConfig(), false);
}
private static IClientConfig createDefaultConfig() {
IClientConfig config = ClientConfigFactory.DEFAULT.newConfig();
config.loadProperties("default");
return config;
}
protected NFHttpClient(String name) {
this(name, createDefaultConfig(), true);
}
protected NFHttpClient(String name, IClientConfig config) {
this(name, config, true);
}
protected NFHttpClient(String name, IClientConfig config, boolean registerMonitor) {
super(new MonitoredConnectionManager(name));
this.name = name;
init(config, registerMonitor);
}
void init(IClientConfig config, boolean registerMonitor) {
HttpParams params = getParams();
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME,
ThreadSafeClientConnManager.class.getName());
HttpClientParams.setRedirecting(params, config.get(CommonClientConfigKey.FollowRedirects, true));
// set up default headers
List<Header> defaultHeaders = new ArrayList<Header>();
defaultHeaders.add(new BasicHeader("Netflix.NFHttpClient.Version", "1.0"));
defaultHeaders.add(new BasicHeader("X-netflix-httpclientname", name));
params.setParameter(ClientPNames.DEFAULT_HEADERS, defaultHeaders);
connPoolCleaner = new ConnectionPoolCleaner(name, this.getConnectionManager(), connectionPoolCleanUpScheduler);
this.retriesProperty = config.getGlobalProperty(RETRIES.format(name));
this.sleepTimeFactorMsProperty = config.getGlobalProperty(SLEEP_TIME_FACTOR_MS.format(name));
setHttpRequestRetryHandler(
new NFHttpMethodRetryHandler(this.name, this.retriesProperty.getOrDefault(), false,
this.sleepTimeFactorMsProperty.getOrDefault()));
tracer = Monitors.newTimer(EXECUTE_TRACER + "-" + name, TimeUnit.MILLISECONDS);
if (registerMonitor) {
Monitors.registerObject(name, this);
}
maxTotalConnectionProperty = config.getDynamicProperty(CommonClientConfigKey.MaxTotalHttpConnections);
maxTotalConnectionProperty.onChange(newValue ->
((ThreadSafeClientConnManager) getConnectionManager()).setMaxTotal(newValue)
);
maxConnectionPerHostProperty = config.getDynamicProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost);
maxConnectionPerHostProperty.onChange(newValue ->
((ThreadSafeClientConnManager) getConnectionManager()).setDefaultMaxPerRoute(newValue)
);
connIdleEvictTimeMilliSeconds = config.getGlobalProperty(CONN_IDLE_EVICT_TIME_MILLIS.format(name));
}
public void initConnectionCleanerTask(){
//set the Properties
connPoolCleaner.setConnIdleEvictTimeMilliSeconds(getConnIdleEvictTimeMilliSeconds());// set FastProperty reference
// for this named httpclient - so we can override it later if we want to
//init the Timer Task
//note that we can change the idletime settings after the start of the Thread
connPoolCleaner.initTask();
}
@Monitor(name = "HttpClient-ConnPoolCleaner", type = DataSourceType.INFORMATIONAL)
public ConnectionPoolCleaner getConnPoolCleaner() {
return connPoolCleaner;
}
@Monitor(name = "HttpClient-ConnIdleEvictTimeMilliSeconds", type = DataSourceType.INFORMATIONAL)
public Property<Integer> getConnIdleEvictTimeMilliSeconds() {
return connIdleEvictTimeMilliSeconds;
}
@Monitor(name="HttpClient-ConnectionsInPool", type = DataSourceType.GAUGE)
public int getConnectionsInPool() {
ClientConnectionManager connectionManager = this.getConnectionManager();
if (connectionManager != null) {
return ((ThreadSafeClientConnManager)connectionManager).getConnectionsInPool();
} else {
return 0;
}
}
@Monitor(name = "HttpClient-MaxTotalConnections", type = DataSourceType.INFORMATIONAL)
public int getMaxTotalConnnections() {
ClientConnectionManager connectionManager = this.getConnectionManager();
if (connectionManager != null) {
return ((ThreadSafeClientConnManager)connectionManager).getMaxTotal();
} else {
return 0;
}
}
@Monitor(name = "HttpClient-MaxConnectionsPerHost", type = DataSourceType.INFORMATIONAL)
public int getMaxConnectionsPerHost() {
ClientConnectionManager connectionManager = this.getConnectionManager();
if (connectionManager != null) {
if(httpRoute == null)
return ((ThreadSafeClientConnManager)connectionManager).getDefaultMaxPerRoute();
else
return ((ThreadSafeClientConnManager)connectionManager).getMaxForRoute(httpRoute);
} else {
return 0;
}
}
@Monitor(name = "HttpClient-NumRetries", type = DataSourceType.INFORMATIONAL)
public int getNumRetries() {
return this.retriesProperty.getOrDefault();
}
public void setConnIdleEvictTimeMilliSeconds(Property<Integer> connIdleEvictTimeMilliSeconds) {
this.connIdleEvictTimeMilliSeconds = connIdleEvictTimeMilliSeconds;
}
@Monitor(name = "HttpClient-SleepTimeFactorMs", type = DataSourceType.INFORMATIONAL)
public int getSleepTimeFactorMs() {
return this.sleepTimeFactorMsProperty.getOrDefault();
}
// copied from httpclient source code
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
// A null target may be acceptable if there is a default target.
// Otherwise, the null target is detected in the director.
HttpHost target = null;
URI requestURI = request.getURI();
if (requestURI.isAbsolute()) {
target = URIUtils.extractHost(requestURI);
if (target == null) {
throw new ClientProtocolException(
"URI does not specify a valid host name: " + requestURI);
}
}
return target;
}
@Override
public <T> T execute(
final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException {
return this.execute(request, responseHandler, null);
}
@Override
public <T> T execute(
final HttpUriRequest request,
final ResponseHandler<? extends T> responseHandler,
final HttpContext context)
throws IOException, ClientProtocolException {
HttpHost target = null;
if(httpHost == null)
target = determineTarget(request);
else
target = httpHost;
return this.execute(target, request, responseHandler, context);
}
@Override
public <T> T execute(
final HttpHost target,
final HttpRequest request,
final ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException {
return this.execute(target, request, responseHandler, null);
}
@Override
public <T> T execute(
final HttpHost target,
final HttpRequest request,
final ResponseHandler<? extends T> responseHandler,
final HttpContext context)
throws IOException, ClientProtocolException {
Stopwatch sw = tracer.start();
try{
// TODO: replaced method.getQueryString() with request.getRequestLine().getUri()
LOGGER.debug("Executing HTTP method: {}, uri: {}", request.getRequestLine().getMethod(), request.getRequestLine().getUri());
return super.execute(target, request, responseHandler, context);
}finally{
sw.stop();
}
}
public void shutdown() {
if (connPoolCleaner != null) {
connPoolCleaner.shutdown();
}
getConnectionManager().shutdown();
}
}
| 3,635 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/ssl/AcceptAllSocketFactory.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4.ssl;
import com.netflix.client.IClientConfigAware;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.IClientConfig;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
*
* SSL Socket factory that will accept all remote endpoints.
*
* This should be used only for testing connections/connectivity.
*
* Following similar pattern as load-balancers here, which is to take an IClientConfig
*
* @author jzarfoss
*
*/
public class AcceptAllSocketFactory extends SSLSocketFactory implements IClientConfigAware {
public AcceptAllSocketFactory() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
super(new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
/**
* In the case of this factory the intent is to ensure that a truststore is not set,
* as this does not make sense in the context of an accept-all policy
*/
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
if (clientConfig == null) {
return;
}
if (clientConfig.getOrDefault(CommonClientConfigKey.TrustStore) != null) {
throw new IllegalArgumentException("Client configured with an AcceptAllSocketFactory cannot utilize a truststore");
}
}
}
| 3,636 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/http4/ssl/KeyStoreAwareSocketFactory.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.http4.ssl;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import com.netflix.client.ssl.AbstractSslContextFactory;
import com.netflix.client.ssl.ClientSslSocketFactoryException;
/**
*
* SocketFactory that remembers what keystore and truststore being used,
* allowing for that information to be queried later.
*
* @author jzarfoss
*
*/
public class KeyStoreAwareSocketFactory extends SSLSocketFactory{
private final KeyStore keyStore;
private final KeyStore trustStore;
public KeyStoreAwareSocketFactory(X509HostnameVerifier hostnameVerifier) throws NoSuchAlgorithmException, KeyStoreException{
super(SSLContext.getDefault(), hostnameVerifier);
this.keyStore = null;
this.trustStore = null;
}
public KeyStoreAwareSocketFactory(final AbstractSslContextFactory abstractFactory) throws ClientSslSocketFactoryException, NoSuchAlgorithmException{
super(abstractFactory == null ? SSLContext.getDefault() : abstractFactory.getSSLContext());
if(abstractFactory == null){
this.keyStore = null;
this.trustStore = null;
}else{
this.keyStore = abstractFactory.getKeyStore();
this.trustStore = abstractFactory.getTrustStore();
}
}
public KeyStoreAwareSocketFactory(final AbstractSslContextFactory abstractFactory, X509HostnameVerifier hostnameVerifier) throws ClientSslSocketFactoryException, NoSuchAlgorithmException{
super(abstractFactory == null ? SSLContext.getDefault() : abstractFactory.getSSLContext(), hostnameVerifier);
if(abstractFactory == null){
this.keyStore = null;
this.trustStore = null;
}else{
this.keyStore = abstractFactory.getKeyStore();
this.trustStore = abstractFactory.getTrustStore();
}
}
public KeyStore getKeyStore(){
return this.keyStore;
}
public KeyStore getTrustStore(){
return this.trustStore;
}
} | 3,637 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client/http/CaseInsensitiveMultiMap.java | package com.netflix.client.http;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
public class CaseInsensitiveMultiMap implements HttpHeaders {
Multimap<String, Entry<String, String>> map = ArrayListMultimap.create();
@Override
public String getFirstValue(String headerName) {
Collection<Entry<String, String>> entries = map.get(headerName.toLowerCase());
if (entries == null || entries.isEmpty()) {
return null;
}
return entries.iterator().next().getValue();
}
@Override
public List<String> getAllValues(String headerName) {
Collection<Entry<String, String>> entries = map.get(headerName.toLowerCase());
List<String> values = Lists.newArrayList();
if (entries != null) {
for (Entry<String, String> entry: entries) {
values.add(entry.getValue());
}
}
return values;
}
@Override
public List<Entry<String, String>> getAllHeaders() {
Collection<Entry<String, String>> all = map.values();
return new ArrayList<Entry<String, String>>(all);
}
@Override
public boolean containsHeader(String name) {
return map.containsKey(name.toLowerCase());
}
public void addHeader(String name, String value) {
if (getAllValues(name).contains(value)) {
return;
}
SimpleEntry<String, String> entry = new SimpleEntry<String, String>(name, value);
map.put(name.toLowerCase(), entry);
}
Map<String, Collection<String>> asMap() {
Multimap<String, String> result = ArrayListMultimap.create();
Collection<Entry<String, String>> all = map.values();
for (Entry<String, String> entry: all) {
result.put(entry.getKey(), entry.getValue());
}
return result.asMap();
}
}
| 3,638 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpHeaders.java | package com.netflix.client.http;
import java.util.List;
import java.util.Map.Entry;
public interface HttpHeaders {
public String getFirstValue(String headerName);
public List<String> getAllValues(String headerName);
public List<Entry<String, String>> getAllHeaders();
public boolean containsHeader(String name);
}
| 3,639 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpRequest.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client.http;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.netflix.client.ClientRequest;
import com.netflix.client.config.IClientConfig;
/**
* Request for HTTP communication.
*
* @author awang
*
*/
public class HttpRequest extends ClientRequest {
public enum Verb {
GET("GET"),
PUT("PUT"),
POST("POST"),
DELETE("DELETE"),
OPTIONS("OPTIONS"),
HEAD("HEAD");
private final String verb; // http method
Verb(String verb) {
this.verb = verb;
}
public String verb() {
return verb;
}
}
protected CaseInsensitiveMultiMap httpHeaders = new CaseInsensitiveMultiMap();
protected Multimap<String, String> queryParams = ArrayListMultimap.create();
private Object entity;
protected Verb verb;
HttpRequest() {
this.verb = Verb.GET;
}
public static class Builder {
private HttpRequest request = new HttpRequest();
public Builder() {
}
public Builder(HttpRequest request) {
this.request = request;
}
public Builder uri(URI uri) {
request.setUri(uri);
return this;
}
public Builder uri(String uri) {
try {
request.setUri(new URI(uri));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return this;
}
public Builder header(String name, String value) {
request.httpHeaders.addHeader(name, value);
return this;
}
Builder queryParams(Multimap<String, String> queryParams) {
request.queryParams = queryParams;
return this;
}
/**
* @deprecated request configuration should be now be passed
* as a method parameter to client's execution API
*/
@Deprecated
public Builder overrideConfig(IClientConfig config) {
request.setOverrideConfig(config);
return this;
}
Builder headers(CaseInsensitiveMultiMap headers) {
request.httpHeaders = headers;
return this;
}
public Builder setRetriable(boolean retriable) {
request.setRetriable(retriable);
return this;
}
/**
* @deprecated see {@link #queryParam(String, String)}
*/
@Deprecated
public Builder queryParams(String name, String value) {
request.queryParams.put(name, value);
return this;
}
public Builder queryParam(String name, String value) {
request.queryParams.put(name, value);
return this;
}
public Builder entity(Object entity) {
request.entity = entity;
return this;
}
public Builder verb(Verb verb) {
request.verb = verb;
return this;
}
public Builder loadBalancerKey(Object loadBalancerKey) {
request.setLoadBalancerKey(loadBalancerKey);
return this;
}
public HttpRequest build() {
return request;
}
}
public Map<String, Collection<String>> getQueryParams() {
return queryParams.asMap();
}
public Verb getVerb() {
return verb;
}
/**
* Replaced by {@link #getHttpHeaders()}
*/
@Deprecated
public Map<String, Collection<String>> getHeaders() {
return httpHeaders.asMap();
}
public HttpHeaders getHttpHeaders() {
return httpHeaders;
}
public Object getEntity() {
return entity;
}
/**
* Test if the request is retriable. If the request is
* a {@link Verb#GET} and {@link Builder#setRetriable(boolean)}
* is not called, returns true. Otherwise, returns value passed in
* {@link Builder#setRetriable(boolean)}
*/
@Override
public boolean isRetriable() {
if (this.verb == Verb.GET && isRetriable == null) {
return true;
}
return super.isRetriable();
}
public static Builder newBuilder() {
return new Builder();
}
public static Builder newBuilder(HttpRequest toCopy) {
return new Builder(toCopy);
}
/**
* Return a new instance of HttpRequest replacing the URI.
*/
@Override
public HttpRequest replaceUri(URI newURI) {
return (new Builder()).uri(newURI)
.headers(this.httpHeaders)
.overrideConfig(this.getOverrideConfig())
.queryParams(this.queryParams)
.setRetriable(this.isRetriable())
.loadBalancerKey(this.getLoadBalancerKey())
.verb(this.getVerb())
.entity(this.entity)
.build();
}
}
| 3,640 |
0 | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client | Create_ds/ribbon/ribbon-httpclient/src/main/java/com/netflix/client/http/HttpResponse.java | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.client.http;
import com.google.common.reflect.TypeToken;
import com.netflix.client.IResponse;
import java.io.Closeable;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
/**
* Response for HTTP communication.
*
* @author awang
*
*/
public interface HttpResponse extends IResponse, Closeable {
/**
* Get the HTTP status code.
*/
public int getStatus();
/**
* Get the reason phrase of HTTP status
*/
public String getStatusLine();
/**
* @see #getHttpHeaders()
*/
@Override
@Deprecated
public Map<String, Collection<String>> getHeaders();
public HttpHeaders getHttpHeaders();
public void close();
public InputStream getInputStream();
public boolean hasEntity();
public <T> T getEntity(Class<T> type) throws Exception;
public <T> T getEntity(Type type) throws Exception;
/**
* @deprecated use {@link #getEntity(Type)}
*/
@Deprecated
public <T> T getEntity(TypeToken<T> type) throws Exception;
}
| 3,641 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/EvCacheAnnotationTest.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy;
import com.netflix.ribbon.CacheProvider;
import com.netflix.ribbon.RibbonRequest;
import com.netflix.ribbon.evache.EvCacheProvider;
import com.netflix.ribbon.http.HttpRequestBuilder;
import com.netflix.ribbon.http.HttpRequestTemplate;
import com.netflix.ribbon.http.HttpRequestTemplate.Builder;
import com.netflix.ribbon.http.HttpResourceGroup;
import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.MovieFallbackHandler;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.SampleHttpResponseValidator;
import com.netflix.ribbon.proxy.sample.SampleMovieServiceWithEVCache;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static com.netflix.ribbon.proxy.Utils.methodByName;
import static junit.framework.Assert.assertEquals;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.*;
/**
* @author Tomasz Bak
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({MethodTemplateExecutor.class})
@PowerMockIgnore("javax.management.*")
public class EvCacheAnnotationTest {
@Mock
private RibbonRequest ribbonRequestMock = createMock(RibbonRequest.class);
@Mock
private HttpRequestBuilder requestBuilderMock = createMock(HttpRequestBuilder.class);
@Mock
private Builder httpRequestTemplateBuilderMock = createMock(Builder.class);
@Mock
private HttpRequestTemplate httpRequestTemplateMock = createMock(HttpRequestTemplate.class);
@Mock
private HttpResourceGroup httpResourceGroupMock = createMock(HttpResourceGroup.class);
@BeforeClass
public static void setup() {
RibbonDynamicProxy.registerAnnotationProcessors(AnnotationProcessorsProvider.DEFAULT);
}
@Before
public void setUp() throws Exception {
expect(requestBuilderMock.build()).andReturn(ribbonRequestMock);
expect(httpRequestTemplateBuilderMock.build()).andReturn(httpRequestTemplateMock);
expect(httpRequestTemplateMock.requestBuilder()).andReturn(requestBuilderMock);
}
@Test
public void testGetQueryWithDomainObjectResult() throws Exception {
expectUrlBase("GET", "/movies/{id}");
expect(requestBuilderMock.withRequestProperty("id", "id123")).andReturn(requestBuilderMock);
expect(httpResourceGroupMock.newTemplateBuilder("findMovieById")).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader1", "value1.1")).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader1", "value1.2")).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withHeader("X-MyHeader2", "value2")).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withRequestCacheKey("findMovieById/{id}")).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withFallbackProvider(anyObject(MovieFallbackHandler.class))).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withResponseValidator(anyObject(SampleHttpResponseValidator.class))).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withCacheProvider(anyObject(String.class), anyObject(CacheProvider.class))).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withCacheProvider(anyObject(String.class), anyObject(EvCacheProvider.class))).andReturn(httpRequestTemplateBuilderMock);
replayAll();
MethodTemplateExecutor executor = createExecutor(SampleMovieServiceWithEVCache.class, "findMovieById");
RibbonRequest ribbonRequest = executor.executeFromTemplate(new Object[]{"id123"});
verifyAll();
assertEquals(ribbonRequestMock, ribbonRequest);
}
private void expectUrlBase(String method, String path) {
expect(httpRequestTemplateBuilderMock.withMethod(method)).andReturn(httpRequestTemplateBuilderMock);
expect(httpRequestTemplateBuilderMock.withUriTemplate(path)).andReturn(httpRequestTemplateBuilderMock);
}
private MethodTemplateExecutor createExecutor(Class<?> clientInterface, String methodName) {
MethodTemplate methodTemplate = new MethodTemplate(methodByName(clientInterface, methodName));
return new MethodTemplateExecutor(httpResourceGroupMock, methodTemplate, AnnotationProcessorsProvider.DEFAULT);
}
}
| 3,642 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/SampleCacheProviderFactory.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.sample;
import com.netflix.ribbon.CacheProvider;
import com.netflix.ribbon.CacheProviderFactory;
import rx.Observable;
import java.util.Map;
/**
* @author Tomasz Bak
*/
public class SampleCacheProviderFactory implements CacheProviderFactory<Object> {
@Override
public CacheProvider<Object> createCacheProvider() {
return new SampleCacheProvider();
}
public static class SampleCacheProvider implements CacheProvider<Object> {
@Override
public Observable<Object> get(String key, Map requestProperties) {
return null;
}
}
}
| 3,643 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/ResourceGroupClasses.java | package com.netflix.ribbon.proxy.sample;
import com.netflix.ribbon.http.HttpResourceGroup;
/**
* @author Tomasz Bak
*/
public class ResourceGroupClasses {
public static class SampleHttpResourceGroup extends HttpResourceGroup {
public SampleHttpResourceGroup() {
super("myTestGroup");
}
}
}
| 3,644 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/MovieTransformer.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.sample;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.reactivex.netty.channel.ContentTransformer;
/**
* @author Tomasz Bak
*/
public class MovieTransformer implements ContentTransformer<MovieTransformer> {
@Override
public ByteBuf call(MovieTransformer toTransform, ByteBufAllocator byteBufAllocator) {
return null;
}
}
| 3,645 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/MovieServiceInterfaces.java | package com.netflix.ribbon.proxy.sample;
import com.netflix.ribbon.RibbonRequest;
import com.netflix.ribbon.proxy.annotation.*;
import com.netflix.ribbon.proxy.annotation.ClientProperties.Property;
import com.netflix.ribbon.proxy.annotation.Http.Header;
import com.netflix.ribbon.proxy.annotation.Http.HttpMethod;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.MovieFallbackHandler;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.SampleHttpResponseValidator;
import io.netty.buffer.ByteBuf;
import rx.Observable;
import java.util.concurrent.atomic.AtomicReference;
import static com.netflix.ribbon.proxy.sample.ResourceGroupClasses.SampleHttpResourceGroup;
/**
* @author Tomasz Bak
*/
public class MovieServiceInterfaces {
@ClientProperties(properties = {
@Property(name="ReadTimeout", value="2000"),
@Property(name="ConnectTimeout", value="1000"),
@Property(name="MaxAutoRetriesNextServer", value="2")
}, exportToArchaius = true)
public static interface SampleMovieService {
@TemplateName("findMovieById")
@Http(
method = HttpMethod.GET,
uri = "/movies/{id}",
headers = {
@Header(name = "X-MyHeader1", value = "value1.1"),
@Header(name = "X-MyHeader1", value = "value1.2"),
@Header(name = "X-MyHeader2", value = "value2")
})
@Hystrix(
cacheKey = "findMovieById/{id}",
validator = SampleHttpResponseValidator.class,
fallbackHandler = MovieFallbackHandler.class)
@CacheProvider(key = "findMovieById_{id}", provider = SampleCacheProviderFactory.class)
RibbonRequest<ByteBuf> findMovieById(@Var("id") String id);
@TemplateName("findRawMovieById")
@Http(method = HttpMethod.GET, uri = "/rawMovies/{id}")
RibbonRequest<ByteBuf> findRawMovieById(@Var("id") String id);
@TemplateName("findMovie")
@Http(method = HttpMethod.GET, uri = "/movies?name={name}&author={author}")
RibbonRequest<ByteBuf> findMovie(@Var("name") String name, @Var("author") String author);
@TemplateName("registerMovie")
@Http(method = HttpMethod.POST, uri = "/movies")
@Hystrix(cacheKey = "registerMovie", fallbackHandler = MovieFallbackHandler.class)
@ContentTransformerClass(MovieTransformer.class)
RibbonRequest<ByteBuf> registerMovie(@Content Movie movie);
@Http(method = HttpMethod.PUT, uri = "/movies/{id}")
@ContentTransformerClass(MovieTransformer.class)
RibbonRequest<ByteBuf> updateMovie(@Var("id") String id, @Content Movie movie);
@Http(method = HttpMethod.PATCH, uri = "/movies/{id}")
@ContentTransformerClass(MovieTransformer.class)
RibbonRequest<ByteBuf> updateMoviePartial(@Var("id") String id, @Content Movie movie);
@TemplateName("registerTitle")
@Http(method = HttpMethod.POST, uri = "/titles")
@Hystrix(cacheKey = "registerTitle", fallbackHandler = MovieFallbackHandler.class)
RibbonRequest<ByteBuf> registerTitle(@Content String title);
@TemplateName("registerByteBufBinary")
@Http(method = HttpMethod.POST, uri = "/binaries/byteBuf")
@Hystrix(cacheKey = "registerByteBufBinary", fallbackHandler = MovieFallbackHandler.class)
RibbonRequest<ByteBuf> registerByteBufBinary(@Content ByteBuf binary);
@TemplateName("registerByteArrayBinary")
@Http(method = HttpMethod.POST, uri = "/binaries/byteArray")
@Hystrix(cacheKey = "registerByteArrayBinary", fallbackHandler = MovieFallbackHandler.class)
RibbonRequest<ByteBuf> registerByteArrayBinary(@Content byte[] binary);
@TemplateName("deleteMovie")
@Http(method = HttpMethod.DELETE, uri = "/movies/{id}")
RibbonRequest<ByteBuf> deleteMovie(@Var("id") String id);
}
public static interface ShortMovieService {
@TemplateName("findMovieById")
@Http(method = HttpMethod.GET, uri = "/movies/{id}")
RibbonRequest<ByteBuf> findMovieById(@Var("id") String id);
@TemplateName("findMovieById")
@Http(method = HttpMethod.GET, uri = "/movies")
RibbonRequest<ByteBuf> findAll();
}
public static interface BrokenMovieService {
@Http(method = HttpMethod.GET)
Movie returnTypeNotRibbonRequest();
Movie missingHttpAnnotation();
@Http(method = HttpMethod.GET)
RibbonRequest<ByteBuf> multipleContentParameters(@Content Movie content1, @Content Movie content2);
}
@ResourceGroup(name = "testResourceGroup")
public static interface SampleMovieServiceWithResourceGroupNameAnnotation {
}
@ResourceGroup(resourceGroupClass = SampleHttpResourceGroup.class)
public static interface SampleMovieServiceWithResourceGroupClassAnnotation {
}
@ResourceGroup(name = "testResourceGroup", resourceGroupClass = SampleHttpResourceGroup.class)
public static interface BrokenMovieServiceWithResourceGroupNameAndClassAnnotation {
}
@ResourceGroup(name = "testResourceGroup")
public static interface TemplateNameDerivedFromMethodName {
@Http(method = HttpMethod.GET, uri = "/template")
RibbonRequest<ByteBuf> myTemplateName();
}
@ResourceGroup(name = "testResourceGroup")
public static interface HystrixOptionalAnnotationValues {
@TemplateName("hystrix1")
@Http(method = HttpMethod.GET, uri = "/hystrix/1")
@Hystrix(cacheKey = "findMovieById/{id}")
RibbonRequest<ByteBuf> hystrixWithCacheKeyOnly();
@TemplateName("hystrix2")
@Http(method = HttpMethod.GET, uri = "/hystrix/2")
@Hystrix(validator = SampleHttpResponseValidator.class)
RibbonRequest<ByteBuf> hystrixWithValidatorOnly();
@TemplateName("hystrix3")
@Http(method = HttpMethod.GET, uri = "/hystrix/3")
@Hystrix(fallbackHandler = MovieFallbackHandler.class)
RibbonRequest<ByteBuf> hystrixWithFallbackHandlerOnly();
}
@ResourceGroup(name = "testResourceGroup")
public static interface PostsWithDifferentContentTypes {
@TemplateName("rawContentSource")
@Http(method = HttpMethod.POST, uri = "/content/rawContentSource")
@ContentTransformerClass(MovieTransformer.class)
RibbonRequest<ByteBuf> postwithRawContentSource(AtomicReference<Object> arg1, int arg2, @Content Observable<Movie> movie);
@TemplateName("byteBufContent")
@Http(method = HttpMethod.POST, uri = "/content/byteBufContent")
RibbonRequest<ByteBuf> postwithByteBufContent(@Content ByteBuf byteBuf);
@TemplateName("byteArrayContent")
@Http(method = HttpMethod.POST, uri = "/content/byteArrayContent")
RibbonRequest<ByteBuf> postwithByteArrayContent(@Content byte[] bytes);
@TemplateName("stringContent")
@Http(method = HttpMethod.POST, uri = "/content/stringContent")
RibbonRequest<ByteBuf> postwithStringContent(@Content String content);
@TemplateName("movieContent")
@Http(method = HttpMethod.POST, uri = "/content/movieContent")
@ContentTransformerClass(MovieTransformer.class)
RibbonRequest<ByteBuf> postwithMovieContent(@Content Movie movie);
@TemplateName("movieContentBroken")
@Http(method = HttpMethod.POST, uri = "/content/movieContentBroken")
RibbonRequest<ByteBuf> postwithMovieContentBroken(@Content Movie movie);
}
}
| 3,646 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/EvCacheClasses.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.sample;
import com.netflix.evcache.EVCacheTranscoder;
import net.spy.memcached.CachedData;
/**
* @author Tomasz Bak
*/
public class EvCacheClasses {
public static class SampleEVCacheTranscoder implements EVCacheTranscoder<Object> {
@Override
public boolean asyncDecode(CachedData d) {
return false;
}
@Override
public CachedData encode(Object o) {
return null;
}
@Override
public Object decode(CachedData d) {
return null;
}
@Override
public int getMaxSize() {
return 0;
}
}
}
| 3,647 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/HystrixHandlers.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.sample;
import com.netflix.hystrix.HystrixInvokableInfo;
import com.netflix.ribbon.ServerError;
import com.netflix.ribbon.UnsuccessfulResponseException;
import com.netflix.ribbon.http.HttpResponseValidator;
import com.netflix.ribbon.hystrix.FallbackHandler;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
import java.util.Map;
/**
* @author Tomasz Bak
*/
public class HystrixHandlers {
public static class SampleHttpResponseValidator implements HttpResponseValidator {
@Override
public void validate(HttpClientResponse<ByteBuf> response) throws UnsuccessfulResponseException, ServerError {
}
}
public static class MovieFallbackHandler implements FallbackHandler<Movie> {
@Override
public Observable<Movie> getFallback(HystrixInvokableInfo<?> hystrixInfo, Map<String, Object> requestProperties) {
return null;
}
}
}
| 3,648 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/SampleMovieServiceWithEVCache.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.sample;
import com.netflix.ribbon.RibbonRequest;
import com.netflix.ribbon.proxy.annotation.CacheProvider;
import com.netflix.ribbon.proxy.annotation.EvCache;
import com.netflix.ribbon.proxy.annotation.Http;
import com.netflix.ribbon.proxy.annotation.Http.Header;
import com.netflix.ribbon.proxy.annotation.Http.HttpMethod;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.netflix.ribbon.proxy.annotation.TemplateName;
import com.netflix.ribbon.proxy.annotation.Var;
import com.netflix.ribbon.proxy.sample.EvCacheClasses.SampleEVCacheTranscoder;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.MovieFallbackHandler;
import com.netflix.ribbon.proxy.sample.HystrixHandlers.SampleHttpResponseValidator;
import com.netflix.ribbon.proxy.sample.MovieServiceInterfaces.SampleMovieService;
import io.netty.buffer.ByteBuf;
/**
* @author Allen Wang
*/
public interface SampleMovieServiceWithEVCache extends SampleMovieService {
@TemplateName("findMovieById")
@Http(
method = HttpMethod.GET,
uri = "/movies/{id}",
headers = {
@Header(name = "X-MyHeader1", value = "value1.1"),
@Header(name = "X-MyHeader1", value = "value1.2"),
@Header(name = "X-MyHeader2", value = "value2")
})
@Hystrix(
cacheKey = "findMovieById/{id}",
validator = SampleHttpResponseValidator.class,
fallbackHandler = MovieFallbackHandler.class)
@CacheProvider(key = "findMovieById_{id}", provider = SampleCacheProviderFactory.class)
@EvCache(name = "movie-cache", appName = "movieService", key = "movie-{id}", ttl = 50,
enableZoneFallback = true, transcoder = SampleEVCacheTranscoder.class)
RibbonRequest<ByteBuf> findMovieById(@Var("id") String id);
}
| 3,649 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/proxy/sample/Movie.java | package com.netflix.ribbon.proxy.sample;
/**
* @author Tomasz Bak
*/
public class Movie {
}
| 3,650 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/evache/ServiceLoaderTest.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
import com.netflix.ribbon.proxy.processor.AnnotationProcessor;
import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider;
import com.netflix.ribbon.proxy.processor.EVCacheAnnotationProcessor;
import org.junit.Test;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
/**
* @author Allen Wang
*/
public class ServiceLoaderTest {
@Test
public void testServiceLoader() {
AnnotationProcessorsProvider annotations = AnnotationProcessorsProvider.DEFAULT;
List<AnnotationProcessor> processors = annotations.getProcessors();
boolean hasEVCacheProcessor = false;
for (AnnotationProcessor processor: processors) {
Class<?> clazz = processor.getClass();
if (clazz.equals(EVCacheAnnotationProcessor.class)) {
hasEVCacheProcessor = true;
break;
}
}
assertTrue(hasEVCacheProcessor);
}
}
| 3,651 |
0 | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/test/java/com/netflix/ribbon/evache/EvCacheProviderTest.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
import com.netflix.evcache.EVCache;
import com.netflix.evcache.EVCacheException;
import com.netflix.evcache.EVCacheImpl;
import com.netflix.evcache.EVCacheTranscoder;
import com.netflix.ribbon.testutils.TestUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import rx.Notification;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func0;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.easymock.EasyMock.*;
import static org.powermock.api.easymock.PowerMock.*;
/**
* @author Tomasz Bak
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({EVCache.Builder.class, EVCacheImpl.class})
public class EvCacheProviderTest {
@Mock
private EVCacheImpl evCacheImplMock;
@Mock
private Future<String> cacheFutureMock;
@Mock
private EVCacheTranscoder<String> transcoderMock;
@Before
public void setUp() throws Exception {
PowerMock.mockStatic(EVCacheImpl.class);
expectNew(EVCacheImpl.class,
new Class[]{String.class, String.class, int.class, EVCacheTranscoder.class, boolean.class},
anyObject(String.class), anyObject(String.class), anyInt(), anyObject(EVCacheTranscoder.class), anyBoolean()
).andReturn(evCacheImplMock);
}
@Test
public void testAsynchronousAccessFromCache() throws Exception {
expect(evCacheImplMock.<String>getAsynchronous("test1")).andReturn(cacheFutureMock);
expect(cacheFutureMock.isDone()).andReturn(true);
expect(cacheFutureMock.isCancelled()).andReturn(false);
expect(cacheFutureMock.get()).andReturn("value1");
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, null, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
assertEquals("value1", cacheValue.toBlocking().first());
}
@Test
public void testAsynchronousAccessWithTranscoderFromCache() throws Exception {
expect(evCacheImplMock.getAsynchronous("test1", transcoderMock)).andReturn(cacheFutureMock);
expect(cacheFutureMock.isDone()).andReturn(true);
expect(cacheFutureMock.isCancelled()).andReturn(false);
expect(cacheFutureMock.get()).andReturn("value1");
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, transcoderMock, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
assertEquals("value1", cacheValue.toBlocking().first());
}
@Test
public void testCacheMiss() throws Exception {
expect(evCacheImplMock.<String>getAsynchronous("test1")).andReturn(cacheFutureMock);
expect(cacheFutureMock.isDone()).andReturn(true);
expect(cacheFutureMock.isCancelled()).andReturn(false);
expect(cacheFutureMock.get()).andReturn(null);
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, null, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
assertTrue(cacheValue.materialize().toBlocking().first().getThrowable() instanceof CacheMissException);
}
@Test
public void testFailedAsynchronousAccessFromCache() throws Exception {
expect(evCacheImplMock.<String>getAsynchronous("test1")).andThrow(new EVCacheException("cache error"));
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, null, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
Notification<Object> notification = cacheValue.materialize().toBlocking().first();
assertTrue(notification.getThrowable() instanceof CacheFaultException);
}
@Test
public void testCanceledFuture() throws Exception {
expect(evCacheImplMock.getAsynchronous("test1", transcoderMock)).andReturn(cacheFutureMock);
expect(cacheFutureMock.isDone()).andReturn(true);
expect(cacheFutureMock.isCancelled()).andReturn(true);
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, transcoderMock, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
assertTrue(cacheValue.materialize().toBlocking().first().getThrowable() instanceof CacheFaultException);
}
@Test
public void testExceptionResultInFuture() throws Exception {
expect(evCacheImplMock.getAsynchronous("test1", transcoderMock)).andReturn(cacheFutureMock);
expect(cacheFutureMock.isDone()).andReturn(true);
expect(cacheFutureMock.isCancelled()).andReturn(false);
expect(cacheFutureMock.get()).andThrow(new ExecutionException(new RuntimeException("operation failed")));
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, transcoderMock, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
assertTrue(cacheValue.materialize().toBlocking().first().getThrowable() instanceof RuntimeException);
}
@Test
public void testUnsubscribedBeforeFutureCompletes() throws Exception {
expect(evCacheImplMock.getAsynchronous("test1", transcoderMock)).andReturn(cacheFutureMock);
expect(cacheFutureMock.cancel(true)).andReturn(true);
replayAll();
EvCacheOptions options = new EvCacheOptions("testApp", "test-cache", true, 100, transcoderMock, "test{id}");
EvCacheProvider<Object> cacheProvider = new EvCacheProvider<Object>(options);
Observable<Object> cacheValue = cacheProvider.get("test1", null);
Subscription subscription = cacheValue.subscribe();
subscription.unsubscribe();
TestUtils.waitUntilTrueOrTimeout(10000, new Func0<Boolean>() {
@Override
public Boolean call() {
try {
verifyAll();
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
}
}
});
}
}
| 3,652 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/proxy/processor/EVCacheAnnotationProcessor.java | package com.netflix.ribbon.proxy.processor;
import com.netflix.evcache.EVCacheTranscoder;
import com.netflix.ribbon.ResourceGroup.GroupBuilder;
import com.netflix.ribbon.ResourceGroup.TemplateBuilder;
import com.netflix.ribbon.RibbonResourceFactory;
import com.netflix.ribbon.evache.EvCacheOptions;
import com.netflix.ribbon.evache.EvCacheProvider;
import com.netflix.ribbon.proxy.ProxyAnnotationException;
import com.netflix.ribbon.proxy.Utils;
import com.netflix.ribbon.proxy.annotation.EvCache;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author Allen Wang
*/
public class EVCacheAnnotationProcessor implements AnnotationProcessor<GroupBuilder, TemplateBuilder> {
private static final class CacheId {
private final String appName;
private final String cacheName;
CacheId(String appName, String cacheName) {
this.appName = appName;
this.cacheName = cacheName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheId cacheId = (CacheId) o;
if (!appName.equals(cacheId.appName)) {
return false;
}
return cacheName.equals(cacheId.cacheName);
}
@Override
public int hashCode() {
int result = appName.hashCode();
result = 31 * result + cacheName.hashCode();
return result;
}
}
private Map<CacheId, EvCacheProvider<?>> evCacheProviderPool = new HashMap<CacheId, EvCacheProvider<?>>();
@Override
public void process(String templateName, TemplateBuilder templateBuilder, Method method) {
EvCache annotation = method.getAnnotation(EvCache.class);
if (annotation == null) {
return;
}
Class<? extends EVCacheTranscoder<?>>[] transcoderClasses = annotation.transcoder();
EVCacheTranscoder<?> transcoder;
if (transcoderClasses.length == 0) {
transcoder = null;
} else if (transcoderClasses.length > 1) {
throw new ProxyAnnotationException("Multiple transcoders defined on method " + method.getName());
} else {
transcoder = Utils.newInstance(transcoderClasses[0]);
}
EvCacheOptions evCacheOptions = new EvCacheOptions(
annotation.appName(),
annotation.name(),
annotation.enableZoneFallback(),
annotation.ttl(),
transcoder,
annotation.key());
if (evCacheOptions != null) {
CacheId cacheId = new CacheId(evCacheOptions.getAppName(), evCacheOptions.getCacheName());
EvCacheProvider<?> provider = evCacheProviderPool.get(cacheId);
if (provider == null) {
provider = new EvCacheProvider(evCacheOptions);
evCacheProviderPool.put(cacheId, provider);
}
templateBuilder.withCacheProvider(evCacheOptions.getCacheKeyTemplate(), provider);
}
}
@Override
public void process(String groupName, GroupBuilder groupBuilder, RibbonResourceFactory factory, Class<?> interfaceClass) {
}
}
| 3,653 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/proxy | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/proxy/annotation/EvCache.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.proxy.annotation;
import com.netflix.evcache.EVCacheTranscoder;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EvCache {
String name();
String appName();
String key();
int ttl() default 100;
boolean enableZoneFallback() default true;
Class<? extends EVCacheTranscoder<?>>[] transcoder() default {};
}
| 3,654 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/evache/CacheMissException.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
/**
* @author Tomasz Bak
*/
public class CacheMissException extends RuntimeException {
}
| 3,655 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/evache/CacheFaultException.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
/**
* @author Tomasz Bak
*/
public class CacheFaultException extends RuntimeException {
private static final long serialVersionUID = -1672764803141328757L;
public CacheFaultException(String message) {
super(message);
}
public CacheFaultException(String message, Throwable cause) {
super(message, cause);
}
}
| 3,656 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/evache/EvCacheProvider.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
import com.netflix.evcache.EVCache;
import com.netflix.evcache.EVCacheException;
import com.netflix.ribbon.CacheProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
/**
* @author Tomasz Bak
*/
public class EvCacheProvider<T> implements CacheProvider<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(EvCacheProvider.class);
private static final long WATCH_INTERVAL = 1;
private static final FutureObserver FUTURE_OBSERVER;
static {
FUTURE_OBSERVER = new FutureObserver();
FUTURE_OBSERVER.start();
}
private final EvCacheOptions options;
private final EVCache evCache;
public EvCacheProvider(EvCacheOptions options) {
this.options = options;
EVCache.Builder builder = new EVCache.Builder();
if (options.isEnableZoneFallback()) {
builder.enableZoneFallback();
}
builder.setDefaultTTL(options.getTimeToLive());
builder.setAppName(options.getAppName());
builder.setCacheName(options.getCacheName());
evCache = builder.build();
}
@SuppressWarnings("unchecked")
@Override
public Observable<T> get(final String key, Map<String, Object> requestProperties) {
return Observable.create(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
Future<T> getFuture;
try {
if (options.getTranscoder() == null) {
getFuture = evCache.getAsynchronous(key);
} else {
getFuture = (Future<T>) evCache.getAsynchronous(key, options.getTranscoder());
}
FUTURE_OBSERVER.watchFuture(getFuture, subscriber);
} catch (EVCacheException e) {
subscriber.onError(new CacheFaultException("EVCache exception when getting value for key " + key, e));
}
}
});
}
@SuppressWarnings({"unchecked", "rawtypes"})
static final class FutureObserver extends Thread {
private final Map<Future, Subscriber> futureMap = new ConcurrentHashMap<Future, Subscriber>();
FutureObserver() {
super("EvCache-Future-Observer");
setDaemon(true);
}
@Override
public void run() {
while (true) {
for (Map.Entry<Future, Subscriber> f : futureMap.entrySet()) {
Future<?> future = f.getKey();
Subscriber subscriber = f.getValue();
if (subscriber.isUnsubscribed()) {
future.cancel(true);
futureMap.remove(future);
} else if (future.isDone()) {
try {
handleCompletedFuture(future, subscriber);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
futureMap.remove(future);
}
}
}
try {
Thread.sleep(WATCH_INTERVAL);
} catch (InterruptedException e) {
// Never terminate
}
}
}
private static void handleCompletedFuture(Future future, Subscriber subscriber) throws InterruptedException {
if (future.isCancelled()) {
subscriber.onError(new CacheFaultException("cache get request canceled"));
} else {
try {
Object value = future.get();
if (value == null) {
subscriber.onError(new CacheMissException());
} else {
subscriber.onNext(value);
subscriber.onCompleted();
}
} catch (ExecutionException e) {
subscriber.onError(e.getCause());
}
}
}
void watchFuture(Future future, Subscriber<?> subscriber) {
futureMap.put(future, subscriber);
}
}
}
| 3,657 |
0 | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon | Create_ds/ribbon/ribbon-evcache/src/main/java/com/netflix/ribbon/evache/EvCacheOptions.java | /*
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.ribbon.evache;
import com.netflix.evcache.EVCacheTranscoder;
/**
* @author Tomasz Bak
*/
public class EvCacheOptions {
private final String appName;
private final String cacheName;
private final boolean enableZoneFallback;
private final int timeToLive;
private final EVCacheTranscoder<?> transcoder;
private final String cacheKeyTemplate;
public EvCacheOptions(String appName, String cacheName, boolean enableZoneFallback, int timeToLive,
EVCacheTranscoder<?> transcoder, String cacheKeyTemplate) {
this.appName = appName;
this.cacheName = cacheName;
this.enableZoneFallback = enableZoneFallback;
this.timeToLive = timeToLive;
this.transcoder = transcoder;
this.cacheKeyTemplate = cacheKeyTemplate;
}
public String getAppName() {
return appName;
}
public String getCacheName() {
return cacheName;
}
public boolean isEnableZoneFallback() {
return enableZoneFallback;
}
public int getTimeToLive() {
return timeToLive;
}
public EVCacheTranscoder<?> getTranscoder() {
return transcoder;
}
public String getCacheKeyTemplate() {
return cacheKeyTemplate;
}
}
| 3,658 |
0 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2/mock/CallsTest.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public final class CallsTest {
@Test
public void bodyExecute() throws IOException {
Call<String> taco = Calls.response("Taco");
assertEquals("Taco", taco.execute().body());
}
@Test
public void bodyEnqueue() throws IOException {
Call<String> taco = Calls.response("Taco");
final AtomicReference<Response<String>> responseRef = new AtomicReference<>();
taco.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
responseRef.set(response);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
fail();
}
});
assertThat(responseRef.get().body()).isEqualTo("Taco");
}
@Test
public void responseExecute() throws IOException {
Response<String> response = Response.success("Taco");
Call<String> taco = Calls.response(response);
assertFalse(taco.isExecuted());
assertSame(response, taco.execute());
assertTrue(taco.isExecuted());
try {
taco.execute();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Already executed");
}
}
@Test
public void responseEnqueue() {
Response<String> response = Response.success("Taco");
Call<String> taco = Calls.response(response);
assertFalse(taco.isExecuted());
final AtomicReference<Response<String>> responseRef = new AtomicReference<>();
taco.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
responseRef.set(response);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
fail();
}
});
assertSame(response, responseRef.get());
assertTrue(taco.isExecuted());
try {
taco.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
fail();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
fail();
}
});
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Already executed");
}
}
@Test
public void enqueueNullThrows() {
Call<String> taco = Calls.response("Taco");
try {
taco.enqueue(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("callback == null");
}
}
@Test
public void responseCancelExecute() {
Call<String> taco = Calls.response(Response.success("Taco"));
assertFalse(taco.isCanceled());
taco.cancel();
assertTrue(taco.isCanceled());
try {
taco.execute();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("canceled");
}
}
@Test
public void responseCancelEnqueue() throws IOException {
Call<String> taco = Calls.response(Response.success("Taco"));
assertFalse(taco.isCanceled());
taco.cancel();
assertTrue(taco.isCanceled());
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
taco.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
fail();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
}
});
assertThat(failureRef.get()).isInstanceOf(IOException.class).hasMessage("canceled");
}
@Test
public void failureExecute() {
IOException failure = new IOException("Hey");
Call<Object> taco = Calls.failure(failure);
assertFalse(taco.isExecuted());
try {
taco.execute();
fail();
} catch (IOException e) {
assertSame(failure, e);
}
assertTrue(taco.isExecuted());
}
@Test
public void failureExecuteCheckedException() {
CertificateException failure = new CertificateException("Hey");
Call<Object> taco = Calls.failure(failure);
assertFalse(taco.isExecuted());
try {
taco.execute();
fail();
} catch (Exception e) {
assertSame(failure, e);
}
assertTrue(taco.isExecuted());
}
@Test
public void failureEnqueue() {
IOException failure = new IOException("Hey");
Call<Object> taco = Calls.failure(failure);
assertFalse(taco.isExecuted());
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
taco.enqueue(
new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
fail();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
failureRef.set(t);
}
});
assertSame(failure, failureRef.get());
assertTrue(taco.isExecuted());
}
@Test
public void cloneHasOwnState() throws IOException {
Call<String> taco = Calls.response("Taco");
assertEquals("Taco", taco.execute().body());
Call<String> anotherTaco = taco.clone();
assertFalse(anotherTaco.isExecuted());
assertEquals("Taco", anotherTaco.execute().body());
assertTrue(anotherTaco.isExecuted());
}
@Test
public void deferredReturnExecute() throws IOException {
Call<Integer> counts =
Calls.defer(
new Callable<Call<Integer>>() {
private int count = 0;
@Override
public Call<Integer> call() throws Exception {
return Calls.response(++count);
}
});
Call<Integer> a = counts.clone();
Call<Integer> b = counts.clone();
assertEquals(1, b.execute().body().intValue());
assertEquals(2, a.execute().body().intValue());
}
@Test
public void deferredReturnEnqueue() {
Call<Integer> counts =
Calls.defer(
new Callable<Call<Integer>>() {
private int count = 0;
@Override
public Call<Integer> call() throws Exception {
return Calls.response(++count);
}
});
Call<Integer> a = counts.clone();
Call<Integer> b = counts.clone();
final AtomicReference<Response<Integer>> responseRef = new AtomicReference<>();
Callback<Integer> callback =
new Callback<Integer>() {
@Override
public void onResponse(Call<Integer> call, Response<Integer> response) {
responseRef.set(response);
}
@Override
public void onFailure(Call<Integer> call, Throwable t) {
fail();
}
};
b.enqueue(callback);
assertEquals(1, responseRef.get().body().intValue());
a.enqueue(callback);
assertEquals(2, responseRef.get().body().intValue());
}
@Test
public void deferredThrowExecute() throws IOException {
final IOException failure = new IOException("Hey");
Call<Object> failing =
Calls.defer(
() -> {
throw failure;
});
try {
failing.execute();
fail();
} catch (IOException e) {
assertSame(failure, e);
}
}
@Test
public void deferredThrowEnqueue() {
final IOException failure = new IOException("Hey");
Call<Object> failing =
Calls.defer(
() -> {
throw failure;
});
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
failing.enqueue(
new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
fail();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
failureRef.set(t);
}
});
assertSame(failure, failureRef.get());
}
@Test
public void deferredThrowUncheckedExceptionEnqueue() {
final RuntimeException failure = new RuntimeException("Hey");
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
Calls.failure(failure)
.enqueue(
new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
fail();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
failureRef.set(t);
}
});
assertSame(failure, failureRef.get());
}
}
| 3,659 |
0 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2/mock/MockRetrofitTest.java | package retrofit2.mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
import retrofit2.Retrofit;
public final class MockRetrofitTest {
private final Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com").build();
private final NetworkBehavior behavior = NetworkBehavior.create();
private final ExecutorService executor = Executors.newSingleThreadExecutor();
@Test
public void retrofitNullThrows() {
try {
new MockRetrofit.Builder(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("retrofit == null");
}
}
@Test
public void retrofitPropagated() {
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build();
assertThat(mockRetrofit.retrofit()).isSameAs(retrofit);
}
@Test
public void networkBehaviorNullThrows() {
MockRetrofit.Builder builder = new MockRetrofit.Builder(retrofit);
try {
builder.networkBehavior(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("behavior == null");
}
}
@Test
public void networkBehaviorDefault() {
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build();
assertThat(mockRetrofit.networkBehavior()).isNotNull();
}
@Test
public void networkBehaviorPropagated() {
MockRetrofit mockRetrofit =
new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();
assertThat(mockRetrofit.networkBehavior()).isSameAs(behavior);
}
@Test
public void backgroundExecutorNullThrows() {
MockRetrofit.Builder builder = new MockRetrofit.Builder(retrofit);
try {
builder.backgroundExecutor(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("executor == null");
}
}
@Test
public void backgroundExecutorDefault() {
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build();
assertThat(mockRetrofit.backgroundExecutor()).isNotNull();
}
@Test
public void backgroundExecutorPropagated() {
MockRetrofit mockRetrofit =
new MockRetrofit.Builder(retrofit).backgroundExecutor(executor).build();
assertThat(mockRetrofit.backgroundExecutor()).isSameAs(executor);
}
}
| 3,660 |
0 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2/mock/NetworkBehaviorTest.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import okhttp3.ResponseBody;
import org.junit.Test;
import retrofit2.Response;
public final class NetworkBehaviorTest {
private final NetworkBehavior behavior = NetworkBehavior.create(new Random(2847));
@Test
public void defaultThrowable() {
Throwable t = behavior.failureException();
assertThat(t)
.isInstanceOf(IOException.class)
.isExactlyInstanceOf(MockRetrofitIOException.class);
assertThat(t.getStackTrace()).isEmpty();
}
@Test
public void delayMustBePositive() {
try {
behavior.setDelay(-1, SECONDS);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Amount must be positive value.");
}
}
@Test
public void varianceRestrictsRange() {
try {
behavior.setVariancePercent(-13);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Variance percentage must be between 0 and 100.");
}
try {
behavior.setVariancePercent(174);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Variance percentage must be between 0 and 100.");
}
}
@Test
public void failureRestrictsRange() {
try {
behavior.setFailurePercent(-13);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Failure percentage must be between 0 and 100.");
}
try {
behavior.setFailurePercent(174);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Failure percentage must be between 0 and 100.");
}
}
@Test
public void failureExceptionIsNotNull() {
try {
behavior.setFailureException(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("exception == null");
}
}
@Test
public void errorRestrictsRange() {
try {
behavior.setErrorPercent(-13);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Error percentage must be between 0 and 100.");
}
try {
behavior.setErrorPercent(174);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Error percentage must be between 0 and 100.");
}
}
@Test
public void errorFactoryIsNotNull() {
try {
behavior.setErrorFactory(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("errorFactory == null");
}
}
@Test
public void errorFactoryCannotReturnNull() {
behavior.setErrorFactory(() -> null);
try {
behavior.createErrorResponse();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Error factory returned null.");
}
}
@Test
public void errorFactoryCannotThrow() {
final RuntimeException broken = new RuntimeException("Broken");
behavior.setErrorFactory(
() -> {
throw broken;
});
try {
behavior.createErrorResponse();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Error factory threw an exception.");
assertThat(e.getCause()).isSameAs(broken);
}
}
@Test
public void errorFactoryCannotReturnSuccess() {
behavior.setErrorFactory(() -> Response.success("Taco"));
try {
behavior.createErrorResponse();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Error factory returned successful response.");
}
}
@Test
public void errorFactoryCalledEachTime() {
behavior.setErrorFactory(
new Callable<Response<?>>() {
private int code = 500;
@Override
public Response<?> call() throws Exception {
return Response.error(code++, ResponseBody.create(null, new byte[0]));
}
});
assertEquals(500, behavior.createErrorResponse().code());
assertEquals(501, behavior.createErrorResponse().code());
assertEquals(502, behavior.createErrorResponse().code());
}
@Test
public void failurePercentageIsAccurate() {
behavior.setFailurePercent(0);
for (int i = 0; i < 10000; i++) {
assertThat(behavior.calculateIsFailure()).isFalse();
}
behavior.setFailurePercent(3);
int failures = 0;
for (int i = 0; i < 100000; i++) {
if (behavior.calculateIsFailure()) {
failures += 1;
}
}
assertThat(failures).isEqualTo(2964); // ~3% of 100k
}
@Test
public void errorPercentageIsAccurate() {
behavior.setErrorPercent(0);
for (int i = 0; i < 10000; i++) {
assertThat(behavior.calculateIsError()).isFalse();
}
behavior.setErrorPercent(3);
int errors = 0;
for (int i = 0; i < 100000; i++) {
if (behavior.calculateIsError()) {
errors += 1;
}
}
assertThat(errors).isEqualTo(2964); // ~3% of 100k
}
@Test
public void delayVarianceIsAccurate() {
behavior.setDelay(2, SECONDS);
behavior.setVariancePercent(0);
for (int i = 0; i < 100000; i++) {
assertThat(behavior.calculateDelay(MILLISECONDS)).isEqualTo(2000);
}
behavior.setVariancePercent(40);
long lowerBound = Integer.MAX_VALUE;
long upperBound = Integer.MIN_VALUE;
for (int i = 0; i < 100000; i++) {
long delay = behavior.calculateDelay(MILLISECONDS);
if (delay > upperBound) {
upperBound = delay;
}
if (delay < lowerBound) {
lowerBound = delay;
}
}
assertThat(upperBound).isEqualTo(2799); // ~40% above 2000
assertThat(lowerBound).isEqualTo(1200); // ~40% below 2000
}
}
| 3,661 |
0 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/test/java/retrofit2/mock/BehaviorDelegateTest.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public final class BehaviorDelegateTest {
interface DoWorkService {
Call<String> response();
Call<String> failure();
}
private final IOException mockFailure = new IOException("Timeout!");
private final NetworkBehavior behavior = NetworkBehavior.create(new Random(2847));
private DoWorkService service;
@Before
public void setUp() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com").build();
MockRetrofit mockRetrofit =
new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();
final BehaviorDelegate<DoWorkService> delegate = mockRetrofit.create(DoWorkService.class);
service =
new DoWorkService() {
@Override
public Call<String> response() {
Call<String> response = Calls.response("Response!");
return delegate.returning(response).response();
}
@Override
public Call<String> failure() {
Call<String> failure = Calls.failure(mockFailure);
return delegate.returning(failure).failure();
}
};
}
@Test
public void syncFailureThrowsAfterDelay() {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(100);
Call<String> call = service.response();
long startNanos = System.nanoTime();
try {
call.execute();
fail();
} catch (IOException e) {
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
assertThat(e).isSameAs(behavior.failureException());
assertThat(tookMs).isGreaterThanOrEqualTo(100);
}
}
@Test
public void asyncFailureTriggersFailureAfterDelay() throws InterruptedException {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(100);
Call<String> call = service.response();
final long startNanos = System.nanoTime();
final AtomicLong tookMs = new AtomicLong();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
tookMs.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(1, SECONDS));
assertThat(failureRef.get()).isSameAs(behavior.failureException());
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
}
@Test
public void syncSuccessReturnsAfterDelay() throws IOException {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
Call<String> call = service.response();
long startNanos = System.nanoTime();
Response<String> response = call.execute();
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
assertThat(response.body()).isEqualTo("Response!");
assertThat(tookMs).isGreaterThanOrEqualTo(100);
}
@Test
public void asyncSuccessCalledAfterDelay() throws InterruptedException, IOException {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
Call<String> call = service.response();
final long startNanos = System.nanoTime();
final AtomicLong tookMs = new AtomicLong();
final AtomicReference<String> actual = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
tookMs.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
actual.set(response.body());
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
throw new AssertionError();
}
});
assertTrue(latch.await(1, SECONDS));
assertThat(actual.get()).isEqualTo("Response!");
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
}
@Test
public void syncFailureThrownAfterDelay() {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
Call<String> call = service.failure();
long startNanos = System.nanoTime();
try {
call.execute();
fail();
} catch (IOException e) {
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
assertThat(tookMs).isGreaterThanOrEqualTo(100);
assertThat(e).isSameAs(mockFailure);
}
}
@Test
public void asyncFailureCalledAfterDelay() throws InterruptedException {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
Call<String> call = service.failure();
final AtomicLong tookMs = new AtomicLong();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
final long startNanos = System.nanoTime();
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
tookMs.set(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(1, SECONDS));
assertThat(tookMs.get()).isGreaterThanOrEqualTo(100);
assertThat(failureRef.get()).isSameAs(mockFailure);
}
@Test
public void syncCanBeCanceled() throws IOException {
behavior.setDelay(10, SECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
final Call<String> call = service.response();
new Thread(
() -> {
try {
Thread.sleep(100);
call.cancel();
} catch (InterruptedException ignored) {
}
})
.start();
try {
call.execute();
fail();
} catch (IOException e) {
assertThat(e).isExactlyInstanceOf(IOException.class).hasMessage("canceled");
}
}
@Test
public void asyncCanBeCanceled() throws InterruptedException {
behavior.setDelay(10, SECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
final Call<String> call = service.response();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
// TODO we shouldn't need to sleep
Thread.sleep(100); // Ensure the task has started.
call.cancel();
assertTrue(latch.await(1, SECONDS));
assertThat(failureRef.get()).isExactlyInstanceOf(IOException.class).hasMessage("canceled");
}
@Test
public void syncCanceledBeforeStart() throws IOException {
behavior.setDelay(100, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
final Call<String> call = service.response();
call.cancel();
try {
call.execute();
fail();
} catch (IOException e) {
assertThat(e).isExactlyInstanceOf(IOException.class).hasMessage("canceled");
}
}
@Test
public void asyncCanBeCanceledBeforeStart() throws InterruptedException {
behavior.setDelay(10, SECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(0);
final Call<String> call = service.response();
call.cancel();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(1, SECONDS));
assertThat(failureRef.get()).isExactlyInstanceOf(IOException.class).hasMessage("canceled");
}
}
| 3,662 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/Calls.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import okhttp3.Request;
import okio.Timeout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/** Factory methods for creating {@link Call} instances which immediately respond or fail. */
public final class Calls {
/**
* Invokes {@code callable} once for the returned {@link Call} and once for each instance that is
* obtained from {@linkplain Call#clone() cloning} the returned {@link Call}.
*/
public static <T> Call<T> defer(Callable<Call<T>> callable) {
return new DeferredCall<>(callable);
}
public static <T> Call<T> response(@Nullable T successValue) {
return new FakeCall<>(Response.success(successValue), null);
}
public static <T> Call<T> response(Response<T> response) {
return new FakeCall<>(response, null);
}
/** Creates a failed {@link Call} from {@code failure}. */
public static <T> Call<T> failure(IOException failure) {
// TODO delete this overload in Retrofit 3.0.
return new FakeCall<>(null, failure);
}
/**
* Creates a failed {@link Call} from {@code failure}.
*
* <p>Note: When invoking {@link Call#execute() execute()} on the returned {@link Call}, if {@code
* failure} is a {@link RuntimeException}, {@link Error}, or {@link IOException} subtype it is
* thrown directly. Otherwise it is "sneaky thrown" despite not being declared.
*/
public static <T> Call<T> failure(Throwable failure) {
return new FakeCall<>(null, failure);
}
private Calls() {
throw new AssertionError("No instances.");
}
static final class FakeCall<T> implements Call<T> {
private final Response<T> response;
private final Throwable error;
private final AtomicBoolean canceled = new AtomicBoolean();
private final AtomicBoolean executed = new AtomicBoolean();
FakeCall(@Nullable Response<T> response, @Nullable Throwable error) {
if ((response == null) == (error == null)) {
throw new AssertionError("Only one of response or error can be set.");
}
this.response = response;
this.error = error;
}
@Override
public Response<T> execute() throws IOException {
if (!executed.compareAndSet(false, true)) {
throw new IllegalStateException("Already executed");
}
if (canceled.get()) {
throw new IOException("canceled");
}
if (response != null) {
return response;
}
throw FakeCall.<Error>sneakyThrow(error);
}
// Intentionally abusing this feature.
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"})
private static <T extends Throwable> T sneakyThrow(Throwable t) throws T {
throw (T) t;
}
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
@Override
public void enqueue(Callback<T> callback) {
if (callback == null) {
throw new NullPointerException("callback == null");
}
if (!executed.compareAndSet(false, true)) {
throw new IllegalStateException("Already executed");
}
if (canceled.get()) {
callback.onFailure(this, new IOException("canceled"));
} else if (response != null) {
callback.onResponse(this, response);
} else {
callback.onFailure(this, error);
}
}
@Override
public boolean isExecuted() {
return executed.get();
}
@Override
public void cancel() {
canceled.set(true);
}
@Override
public boolean isCanceled() {
return canceled.get();
}
@Override
public Call<T> clone() {
return new FakeCall<>(response, error);
}
@Override
public Request request() {
if (response != null) {
return response.raw().request();
}
return new Request.Builder().url("http://localhost").build();
}
@Override
public Timeout timeout() {
return Timeout.NONE;
}
}
static final class DeferredCall<T> implements Call<T> {
private final Callable<Call<T>> callable;
private @Nullable Call<T> delegate;
DeferredCall(Callable<Call<T>> callable) {
this.callable = callable;
}
private synchronized Call<T> getDelegate() {
Call<T> delegate = this.delegate;
if (delegate == null) {
try {
delegate = callable.call();
} catch (Exception e) {
delegate = failure(e);
}
this.delegate = delegate;
}
return delegate;
}
@Override
public Response<T> execute() throws IOException {
return getDelegate().execute();
}
@Override
public void enqueue(Callback<T> callback) {
getDelegate().enqueue(callback);
}
@Override
public boolean isExecuted() {
return getDelegate().isExecuted();
}
@Override
public void cancel() {
getDelegate().cancel();
}
@Override
public boolean isCanceled() {
return getDelegate().isCanceled();
}
@Override
public Call<T> clone() {
return new DeferredCall<>(callable);
}
@Override
public Request request() {
return getDelegate().request();
}
@Override
public Timeout timeout() {
return getDelegate().timeout();
}
}
}
| 3,663 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/BehaviorDelegate.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import kotlin.coroutines.Continuation;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.KotlinExtensions;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* Applies {@linkplain NetworkBehavior behavior} to responses and adapts them into the appropriate
* return type using the {@linkplain Retrofit#callAdapterFactories() call adapters} of {@link
* Retrofit}.
*
* @see MockRetrofit#create(Class)
*/
public final class BehaviorDelegate<T> {
final Retrofit retrofit;
private final NetworkBehavior behavior;
private final ExecutorService executor;
private final Class<T> service;
BehaviorDelegate(
Retrofit retrofit, NetworkBehavior behavior, ExecutorService executor, Class<T> service) {
this.retrofit = retrofit;
this.behavior = behavior;
this.executor = executor;
this.service = service;
}
public T returningResponse(@Nullable Object response) {
return returning(Calls.response(response));
}
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <R> T returning(Call<R> call) {
final Call<R> behaviorCall = new BehaviorCall<>(behavior, executor, call);
return (T)
Proxy.newProxyInstance(
service.getClassLoader(),
new Class[] {service},
(proxy, method, args) -> {
ServiceMethodAdapterInfo adapterInfo = parseServiceMethodAdapterInfo(method);
Annotation[] methodAnnotations = method.getAnnotations();
CallAdapter<R, T> callAdapter =
(CallAdapter<R, T>)
retrofit.callAdapter(adapterInfo.responseType, methodAnnotations);
T adapted = callAdapter.adapt(behaviorCall);
if (!adapterInfo.isSuspend) {
return adapted;
}
Call<Object> adaptedCall = (Call<Object>) adapted;
Continuation<Object> continuation = (Continuation<Object>) args[args.length - 1];
try {
return adapterInfo.wantsResponse
? KotlinExtensions.awaitResponse(adaptedCall, continuation)
: KotlinExtensions.await(adaptedCall, continuation);
} catch (Exception e) {
return KotlinExtensions.suspendAndThrow(e, continuation);
}
});
}
/**
* Computes the adapter type of the method for lookup via {@link Retrofit#callAdapter} as well as
* information on whether the method is a {@code suspend fun}.
*
* <p>In the case of a Kotlin {@code suspend fun}, the last parameter type is a {@code
* Continuation} whose parameter carries the actual response type. In this case, we return {@code
* Call<T>} where {@code T} is the body type.
*/
private static ServiceMethodAdapterInfo parseServiceMethodAdapterInfo(Method method) {
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (genericParameterTypes.length != 0) {
Type lastParameterType = genericParameterTypes[genericParameterTypes.length - 1];
if (lastParameterType instanceof ParameterizedType) {
ParameterizedType parameterizedLastParameterType = (ParameterizedType) lastParameterType;
try {
if (parameterizedLastParameterType.getRawType() == Continuation.class) {
Type resultType = parameterizedLastParameterType.getActualTypeArguments()[0];
if (resultType instanceof WildcardType) {
resultType = ((WildcardType) resultType).getLowerBounds()[0];
}
if (resultType instanceof ParameterizedType) {
ParameterizedType parameterizedResultType = (ParameterizedType) resultType;
if (parameterizedResultType.getRawType() == Response.class) {
Type bodyType = parameterizedResultType.getActualTypeArguments()[0];
Type callType = new CallParameterizedTypeImpl(bodyType);
return new ServiceMethodAdapterInfo(true, true, callType);
}
}
Type callType = new CallParameterizedTypeImpl(resultType);
return new ServiceMethodAdapterInfo(true, false, callType);
}
} catch (NoClassDefFoundError ignored) {
// Not using coroutines.
}
}
}
return new ServiceMethodAdapterInfo(false, false, method.getGenericReturnType());
}
static final class CallParameterizedTypeImpl implements ParameterizedType {
private final Type bodyType;
CallParameterizedTypeImpl(Type bodyType) {
this.bodyType = bodyType;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[] {bodyType};
}
@Override
public Type getRawType() {
return Call.class;
}
@Override
public @Nullable Type getOwnerType() {
return null;
}
}
static class ServiceMethodAdapterInfo {
final boolean isSuspend;
/**
* Whether the suspend function return type was {@code Response<T>}. Only meaningful if {@link
* #isSuspend} is true.
*/
final boolean wantsResponse;
final Type responseType;
ServiceMethodAdapterInfo(boolean isSuspend, boolean wantsResponse, Type responseType) {
this.isSuspend = isSuspend;
this.wantsResponse = wantsResponse;
this.responseType = responseType;
}
}
}
| 3,664 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/MockRetrofitIOException.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import java.io.IOException;
final class MockRetrofitIOException extends IOException {
MockRetrofitIOException() {
super("Failure triggered by MockRetrofit's NetworkBehavior");
}
}
| 3,665 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/BehaviorCall.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import okhttp3.Request;
import okio.Timeout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
final class BehaviorCall<T> implements Call<T> {
final NetworkBehavior behavior;
final ExecutorService backgroundExecutor;
final Call<T> delegate;
private volatile @Nullable Future<?> task;
volatile boolean canceled;
@GuardedBy("this")
private boolean executed;
BehaviorCall(NetworkBehavior behavior, ExecutorService backgroundExecutor, Call<T> delegate) {
this.behavior = behavior;
this.backgroundExecutor = backgroundExecutor;
this.delegate = delegate;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override
public Call<T> clone() {
return new BehaviorCall<>(behavior, backgroundExecutor, delegate.clone());
}
@Override
public Request request() {
return delegate.request();
}
@Override
public Timeout timeout() {
return delegate.timeout();
}
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
@Override
public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("callback == null");
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed");
executed = true;
}
task =
backgroundExecutor.submit(
new Runnable() {
boolean delaySleep() {
long sleepMs = behavior.calculateDelay(MILLISECONDS);
if (sleepMs > 0) {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
callback.onFailure(BehaviorCall.this, new IOException("canceled", e));
return false;
}
}
return true;
}
@Override
public void run() {
if (canceled) {
callback.onFailure(BehaviorCall.this, new IOException("canceled"));
} else if (behavior.calculateIsFailure()) {
if (delaySleep()) {
callback.onFailure(BehaviorCall.this, behavior.failureException());
}
} else if (behavior.calculateIsError()) {
if (delaySleep()) {
//noinspection unchecked An error response has no body.
callback.onResponse(
BehaviorCall.this, (Response<T>) behavior.createErrorResponse());
}
} else {
delegate.enqueue(
new Callback<T>() {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (delaySleep()) {
callback.onResponse(call, response);
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
if (delaySleep()) {
callback.onFailure(call, t);
}
}
});
}
}
});
}
@Override
public synchronized boolean isExecuted() {
return executed;
}
@Override
public Response<T> execute() throws IOException {
final AtomicReference<Response<T>> responseRef = new AtomicReference<>();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
enqueue(
new Callback<T>() {
@Override
public void onResponse(Call<T> call, Response<T> response) {
responseRef.set(response);
latch.countDown();
}
@Override
public void onFailure(Call<T> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
throw new IOException("canceled", e);
}
Response<T> response = responseRef.get();
if (response != null) return response;
Throwable failure = failureRef.get();
if (failure instanceof RuntimeException) throw (RuntimeException) failure;
if (failure instanceof IOException) throw (IOException) failure;
throw new RuntimeException(failure);
}
@Override
public void cancel() {
canceled = true;
Future<?> task = this.task;
if (task != null) {
task.cancel(true);
}
}
@Override
public boolean isCanceled() {
return canceled;
}
}
| 3,666 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/MockRetrofit.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Nullable;
import retrofit2.Retrofit;
public final class MockRetrofit {
private final Retrofit retrofit;
private final NetworkBehavior behavior;
private final ExecutorService executor;
MockRetrofit(Retrofit retrofit, NetworkBehavior behavior, ExecutorService executor) {
this.retrofit = retrofit;
this.behavior = behavior;
this.executor = executor;
}
public Retrofit retrofit() {
return retrofit;
}
public NetworkBehavior networkBehavior() {
return behavior;
}
public Executor backgroundExecutor() {
return executor;
}
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <T> BehaviorDelegate<T> create(Class<T> service) {
return new BehaviorDelegate<>(retrofit, behavior, executor, service);
}
public static final class Builder {
private final Retrofit retrofit;
private @Nullable NetworkBehavior behavior;
private @Nullable ExecutorService executor;
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public Builder(Retrofit retrofit) {
if (retrofit == null) throw new NullPointerException("retrofit == null");
this.retrofit = retrofit;
}
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public Builder networkBehavior(NetworkBehavior behavior) {
if (behavior == null) throw new NullPointerException("behavior == null");
this.behavior = behavior;
return this;
}
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public Builder backgroundExecutor(ExecutorService executor) {
if (executor == null) throw new NullPointerException("executor == null");
this.executor = executor;
return this;
}
public MockRetrofit build() {
if (behavior == null) behavior = NetworkBehavior.create();
if (executor == null) executor = Executors.newCachedThreadPool();
return new MockRetrofit(retrofit, behavior, executor);
}
}
}
| 3,667 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/NetworkBehavior.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.mock;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import okhttp3.ResponseBody;
import retrofit2.Response;
/**
* A simple emulation of the behavior of network calls.
*
* <p>This class models three properties of a network:
*
* <ul>
* <li>Delay – the time it takes before a response is received (successful or otherwise).
* <li>Variance – the amount of fluctuation of the delay to be faster or slower.
* <li>Failure - the percentage of operations which fail (such as {@link IOException}).
* </ul>
*
* Behavior can be applied to a Retrofit interface with {@link MockRetrofit}. Behavior can also be
* applied elsewhere using {@link #calculateDelay(TimeUnit)} and {@link #calculateIsFailure()}.
*
* <p>By default, instances of this class will use a 2 second delay with 40% variance. Failures will
* occur 3% of the time. HTTP errors will occur 0% of the time.
*/
public final class NetworkBehavior {
private static final int DEFAULT_DELAY_MS = 2000; // Network calls will take 2 seconds.
private static final int DEFAULT_VARIANCE_PERCENT = 40; // Network delay varies by ±40%.
private static final int DEFAULT_FAILURE_PERCENT = 3; // 3% of network calls will fail.
private static final int DEFAULT_ERROR_PERCENT = 0; // 0% of network calls will return errors.
/** Create an instance with default behavior. */
public static NetworkBehavior create() {
return new NetworkBehavior(new Random());
}
/**
* Create an instance with default behavior which uses {@code random} to control variance and
* failure calculation.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static NetworkBehavior create(Random random) {
if (random == null) throw new NullPointerException("random == null");
return new NetworkBehavior(random);
}
private final Random random;
private volatile long delayMs = DEFAULT_DELAY_MS;
private volatile int variancePercent = DEFAULT_VARIANCE_PERCENT;
private volatile int failurePercent = DEFAULT_FAILURE_PERCENT;
private volatile Throwable failureException;
private volatile int errorPercent = DEFAULT_ERROR_PERCENT;
private volatile Callable<Response<?>> errorFactory =
() -> Response.error(500, ResponseBody.create(null, new byte[0]));
private NetworkBehavior(Random random) {
this.random = random;
failureException = new MockRetrofitIOException();
failureException.setStackTrace(new StackTraceElement[0]);
}
/** Set the network round trip delay. */
public void setDelay(long amount, TimeUnit unit) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be positive value.");
}
this.delayMs = unit.toMillis(amount);
}
/** The network round trip delay. */
public long delay(TimeUnit unit) {
return MILLISECONDS.convert(delayMs, unit);
}
/** Set the plus-or-minus variance percentage of the network round trip delay. */
public void setVariancePercent(int variancePercent) {
checkPercentageValidity(variancePercent, "Variance percentage must be between 0 and 100.");
this.variancePercent = variancePercent;
}
/** The plus-or-minus variance percentage of the network round trip delay. */
public int variancePercent() {
return variancePercent;
}
/** Set the percentage of calls to {@link #calculateIsFailure()} that return {@code true}. */
public void setFailurePercent(int failurePercent) {
checkPercentageValidity(failurePercent, "Failure percentage must be between 0 and 100.");
this.failurePercent = failurePercent;
}
/** The percentage of calls to {@link #calculateIsFailure()} that return {@code true}. */
public int failurePercent() {
return failurePercent;
}
/**
* Set the exception to be used when a failure is triggered.
*
* <p>It is a best practice to remove the stack trace from {@code exception} since it can
* misleadingly point to code unrelated to this class.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public void setFailureException(Throwable exception) {
if (exception == null) {
throw new NullPointerException("exception == null");
}
this.failureException = exception;
}
/** The exception to be used when a failure is triggered. */
public Throwable failureException() {
return failureException;
}
/** The percentage of calls to {@link #calculateIsError()} that return {@code true}. */
public int errorPercent() {
return errorPercent;
}
/** Set the percentage of calls to {@link #calculateIsError()} that return {@code true}. */
public void setErrorPercent(int errorPercent) {
checkPercentageValidity(errorPercent, "Error percentage must be between 0 and 100.");
this.errorPercent = errorPercent;
}
/**
* Set the error response factory to be used when an error is triggered. This factory may only
* return responses for which {@link Response#isSuccessful()} returns false.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public void setErrorFactory(Callable<Response<?>> errorFactory) {
if (errorFactory == null) {
throw new NullPointerException("errorFactory == null");
}
this.errorFactory = errorFactory;
}
/** The HTTP error to be used when an error is triggered. */
public Response<?> createErrorResponse() {
Response<?> call;
try {
call = errorFactory.call();
} catch (Exception e) {
throw new IllegalStateException("Error factory threw an exception.", e);
}
if (call == null) {
throw new IllegalStateException("Error factory returned null.");
}
if (call.isSuccessful()) {
throw new IllegalStateException("Error factory returned successful response.");
}
return call;
}
/**
* Randomly determine whether this call should result in a network failure in accordance with
* configured behavior. When true, {@link #failureException()} should be thrown.
*/
public boolean calculateIsFailure() {
return random.nextInt(100) < failurePercent;
}
/**
* Randomly determine whether this call should result in an HTTP error in accordance with
* configured behavior. When true, {@link #createErrorResponse()} should be returned.
*/
public boolean calculateIsError() {
return random.nextInt(100) < errorPercent;
}
/**
* Get the delay that should be used for delaying a response in accordance with configured
* behavior.
*/
public long calculateDelay(TimeUnit unit) {
float delta = variancePercent / 100f; // e.g., 20 / 100f == 0.2f
float lowerBound = 1f - delta; // 0.2f --> 0.8f
float upperBound = 1f + delta; // 0.2f --> 1.2f
float bound = upperBound - lowerBound; // 1.2f - 0.8f == 0.4f
float delayPercent = lowerBound + (random.nextFloat() * bound); // 0.8 + (rnd * 0.4)
long callDelayMs = (long) (delayMs * delayPercent);
return MILLISECONDS.convert(callDelayMs, unit);
}
private static void checkPercentageValidity(int percentage, String message) {
if (percentage < 0 || percentage > 100) {
throw new IllegalArgumentException(message);
}
}
}
| 3,668 |
0 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2 | Create_ds/retrofit/retrofit-mock/src/main/java/retrofit2/mock/package-info.java | @retrofit2.internal.EverythingIsNonNull
package retrofit2.mock;
| 3,669 |
0 | Create_ds/retrofit/retrofit/robovm-test/src/main/java | Create_ds/retrofit/retrofit/robovm-test/src/main/java/retrofit2/RoboVmPlatformTest.java | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
public final class RoboVmPlatformTest {
public static void main(String[] args) {
Platform platform = Platform.get();
if (platform.createDefaultCallAdapterFactories(null).size() > 1) {
// Everyone gets the callback executor adapter. If RoboVM was correctly detected it will NOT
// get the Java 8-supporting CompletableFuture call adapter factory.
System.exit(1);
}
}
private RoboVmPlatformTest() {
}
}
| 3,670 |
0 | Create_ds/retrofit/retrofit/kotlin-test/src/test/java | Create_ds/retrofit/retrofit/kotlin-test/src/test/java/retrofit2/KotlinSuspendRawTest.java | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import kotlin.coroutines.Continuation;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.GET;
/**
* This code path can only be tested from Java because Kotlin does not allow you specify a raw
* Response type. Win! We still test this codepath for completeness.
*/
public final class KotlinSuspendRawTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Object body(Continuation<? super Response> response);
}
@Test
public void raw() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
Service service = retrofit.create(Service.class);
try {
service.body(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Response must include generic type (e.g., Response<String>)\n"
+ " for method Service.body");
}
}
}
| 3,671 |
0 | Create_ds/retrofit/retrofit/kotlin-test/src/test/java | Create_ds/retrofit/retrofit/kotlin-test/src/test/java/retrofit2/KotlinUnitTest.java | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import kotlin.Unit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.GET;
import retrofit2.http.HEAD;
public final class KotlinUnitTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Call<Unit> empty();
@HEAD("/")
Call<Unit> head();
}
@Test
public void unitGet() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Response<Unit> response = example.empty().execute();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(Unit.INSTANCE);
}
@Test
public void unitHead() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Response<Unit> response = example.head().execute();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(Unit.INSTANCE);
}
}
| 3,672 |
0 | Create_ds/retrofit/retrofit/kotlin-test/src/test/java | Create_ds/retrofit/retrofit/kotlin-test/src/test/java/retrofit2/KotlinRequestFactoryTest.java | package retrofit2;
import kotlin.Unit;
import okhttp3.Request;
import org.junit.Test;
import retrofit2.http.HEAD;
import static org.assertj.core.api.Assertions.assertThat;
import static retrofit2.TestingUtils.buildRequest;
public final class KotlinRequestFactoryTest {
@Test
public void headUnit() {
class Example {
@HEAD("/foo/bar/")
Call<Unit> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("HEAD");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
}
| 3,673 |
0 | Create_ds/retrofit/retrofit/android-test/src/androidTest/java | Create_ds/retrofit/retrofit/android-test/src/androidTest/java/retrofit2/BasicCallTest.java | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import java.io.IOException;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.GET;
import static org.junit.Assert.assertEquals;
public final class BasicCallTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/") Call<ResponseBody> getBody();
}
@Test public void responseBody() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("1234"));
Response<ResponseBody> response = example.getBody().execute();
assertEquals("1234", response.body().string());
}
}
| 3,674 |
0 | Create_ds/retrofit/retrofit/android-test/src/androidTest/java | Create_ds/retrofit/retrofit/android-test/src/androidTest/java/retrofit2/DefaultMethodsAndroidTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import androidx.test.filters.SdkSuppress;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public final class DefaultMethodsAndroidTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Example {
@GET("/")
Call<String> user(@Query("name") String name);
default Call<String> user() {
return user("hey");
}
}
@Test
@SdkSuppress(minSdkVersion = 24, maxSdkVersion = 25)
public void failsOnApi24And25() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Example example = retrofit.create(Example.class);
try {
example.user();
fail();
} catch (UnsupportedOperationException e) {
assertThat(e).hasMessage("Calling default methods on API 24 and 25 is not supported");
}
}
@Test
@SdkSuppress(minSdkVersion = 26)
public void doesNotFailOnApi26() throws IOException, InterruptedException {
server.enqueue(new MockResponse());
server.enqueue(new MockResponse());
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Example example = retrofit.create(Example.class);
example.user().execute();
assertThat(server.takeRequest().getRequestUrl().queryParameter("name")).isEqualTo("hey");
example.user("hi").execute();
assertThat(server.takeRequest().getRequestUrl().queryParameter("name")).isEqualTo("hi");
}
}
| 3,675 |
0 | Create_ds/retrofit/retrofit/android-test/src/androidTest/java | Create_ds/retrofit/retrofit/android-test/src/androidTest/java/retrofit2/CompletableFutureAndroidTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import androidx.test.filters.SdkSuppress;
import java.util.concurrent.CompletableFuture;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.GET;
import static org.assertj.core.api.Assertions.assertThat;
@SdkSuppress(minSdkVersion = 24)
public final class CompletableFutureAndroidTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
CompletableFuture<String> endpoint();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
service = retrofit.create(Service.class);
}
@Test
public void completableFutureApi24() throws Exception {
server.enqueue(new MockResponse().setBody("Hi"));
CompletableFuture<String> future = service.endpoint();
assertThat(future.get()).isEqualTo("Hi");
}
}
| 3,676 |
0 | Create_ds/retrofit/retrofit/android-test/src/androidTest/java | Create_ds/retrofit/retrofit/android-test/src/androidTest/java/retrofit2/UriAndroidTest.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import android.net.Uri;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.http.GET;
import retrofit2.http.Url;
import static org.assertj.core.api.Assertions.assertThat;
public final class UriAndroidTest {
@Rule public final MockWebServer server1 = new MockWebServer();
@Rule public final MockWebServer server2 = new MockWebServer();
interface Service {
@GET
Call<ResponseBody> method(@Url Uri url);
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server1.url("/"))
.build();
service = retrofit.create(Service.class);
}
@Test
public void getWithAndroidUriUrl() throws IOException, InterruptedException {
server1.enqueue(new MockResponse().setBody("Hi"));
service.method(Uri.parse("foo/bar/")).execute();
assertThat(server1.takeRequest().getRequestUrl()).isEqualTo(server1.url("foo/bar/"));
}
@Test
public void getWithAndroidUriUrlAbsolute() throws IOException, InterruptedException {
server2.enqueue(new MockResponse().setBody("Hi"));
HttpUrl url = server2.url("/");
service.method(Uri.parse(url.toString())).execute();
assertThat(server2.takeRequest().getRequestUrl()).isEqualTo(url);
}
}
| 3,677 |
0 | Create_ds/retrofit/retrofit/android-test/src/androidTest/java | Create_ds/retrofit/retrofit/android-test/src/androidTest/java/retrofit2/OptionalConverterFactoryAndroidTest.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import androidx.test.filters.SdkSuppress;
import java.io.IOException;
import java.util.Optional;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ObjectInstanceConverterFactory;
import retrofit2.http.GET;
import static org.assertj.core.api.Assertions.assertThat;
@SdkSuppress(minSdkVersion = 24)
public final class OptionalConverterFactoryAndroidTest {
interface Service {
@GET("/")
Call<Optional<Object>> optional();
@GET("/")
Call<Object> object();
}
@Rule public final MockWebServer server = new MockWebServer();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ObjectInstanceConverterFactory())
.build();
service = retrofit.create(Service.class);
}
@Test
public void optionalApi24() throws IOException {
server.enqueue(new MockResponse());
Optional<Object> optional = service.optional().execute().body();
assertThat(optional.get()).isSameAs(ObjectInstanceConverterFactory.VALUE);
}
@Test
public void onlyMatchesOptional() throws IOException {
server.enqueue(new MockResponse());
Object body = service.object().execute().body();
assertThat(body).isSameAs(ObjectInstanceConverterFactory.VALUE);
}
}
| 3,678 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/TestingUtils.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import java.lang.reflect.Method;
import java.util.Arrays;
import okhttp3.Request;
import retrofit2.helpers.ToStringConverterFactory;
final class TestingUtils {
static <T> Request buildRequest(Class<T> cls, Retrofit.Builder builder, Object... args) {
okhttp3.Call.Factory callFactory =
request -> {
throw new UnsupportedOperationException("Not implemented");
};
Retrofit retrofit = builder.callFactory(callFactory).build();
Method method = onlyMethod(cls);
try {
return RequestFactory.parseAnnotations(retrofit, method).create(args);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new AssertionError(e);
}
}
static <T> Request buildRequest(Class<T> cls, Object... args) {
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(new ToStringConverterFactory());
return buildRequest(cls, retrofitBuilder, args);
}
static Method onlyMethod(Class c) {
Method[] declaredMethods = c.getDeclaredMethods();
if (declaredMethods.length == 1) {
return declaredMethods[0];
}
throw new IllegalArgumentException("More than one method declared.");
}
static String repeat(char c, int times) {
char[] cs = new char[times];
Arrays.fill(cs, c);
return new String(cs);
}
}
| 3,679 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/ToStringConverterFactory.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public class ToStringConverterFactory extends Converter.Factory {
static final MediaType MEDIA_TYPE = MediaType.get("text/plain");
@Override
public @Nullable Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return ResponseBody::string;
}
return null;
}
@Override
public @Nullable Converter<String, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
if (String.class.equals(type)) {
return value -> RequestBody.create(MEDIA_TYPE, value);
}
return null;
}
}
| 3,680 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/NonMatchingConverterFactory.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public final class NonMatchingConverterFactory extends Converter.Factory {
public boolean called;
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
called = true;
return null;
}
@Override
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
called = true;
return null;
}
@Override
public @Nullable Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
called = true;
return null;
}
}
| 3,681 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/NullObjectConverterFactory.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import retrofit2.Converter;
import retrofit2.Retrofit;
/** Always converts to null. */
public final class NullObjectConverterFactory extends Converter.Factory {
@Override
public Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return new Converter<Object, String>() {
@Override
public String convert(Object value) throws IOException {
return null;
}
};
}
}
| 3,682 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/DelegatingCallAdapterFactory.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
public final class DelegatingCallAdapterFactory extends CallAdapter.Factory {
public boolean called;
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
called = true;
return retrofit.nextCallAdapter(this, returnType, annotations);
}
}
| 3,683 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/NonMatchingCallAdapterFactory.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;
public final class NonMatchingCallAdapterFactory extends CallAdapter.Factory {
public boolean called;
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
called = true;
return null;
}
}
| 3,684 |
0 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2 | Create_ds/retrofit/retrofit/test-helpers/src/main/java/retrofit2/helpers/ObjectInstanceConverterFactory.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.helpers;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public final class ObjectInstanceConverterFactory extends Converter.Factory {
public static final Object VALUE = new Object();
@Override
public @Nullable Converter<ResponseBody, Object> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
if (type != Object.class) {
return null;
}
return value -> VALUE;
}
}
| 3,685 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/RetrofitTest.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AT_START;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.DelegatingCallAdapterFactory;
import retrofit2.helpers.NonMatchingCallAdapterFactory;
import retrofit2.helpers.NonMatchingConverterFactory;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public final class RetrofitTest {
@Rule public final MockWebServer server = new MockWebServer();
interface CallMethod {
@GET("/")
Call<String> disallowed();
@POST("/")
Call<ResponseBody> disallowed(@Body String body);
@GET("/")
Call<retrofit2.Response> badType1();
@GET("/")
Call<okhttp3.Response> badType2();
@GET("/")
Call<ResponseBody> getResponseBody();
@SkipCallbackExecutor
@GET("/")
Call<ResponseBody> getResponseBodySkippedExecutor();
@GET("/")
Call<Void> getVoid();
@POST("/")
Call<ResponseBody> postRequestBody(@Body RequestBody body);
@GET("/")
Call<ResponseBody> queryString(@Query("foo") String foo);
@GET("/")
Call<ResponseBody> queryObject(@Query("foo") Object foo);
}
interface FutureMethod {
@GET("/")
Future<String> method();
}
interface Extending extends CallMethod {}
interface TypeParam<T> {}
interface ExtendingTypeParam extends TypeParam<String> {}
interface StringService {
@GET("/")
String get();
}
interface UnresolvableResponseType {
@GET("/")
<T> Call<T> typeVariable();
@GET("/")
<T extends ResponseBody> Call<T> typeVariableUpperBound();
@GET("/")
<T> Call<List<Map<String, Set<T[]>>>> crazy();
@GET("/")
Call<?> wildcard();
@GET("/")
Call<? extends ResponseBody> wildcardUpperBound();
}
interface UnresolvableParameterType {
@POST("/")
<T> Call<ResponseBody> typeVariable(@Body T body);
@POST("/")
<T extends RequestBody> Call<ResponseBody> typeVariableUpperBound(@Body T body);
@POST("/")
<T> Call<ResponseBody> crazy(@Body List<Map<String, Set<T[]>>> body);
@POST("/")
Call<ResponseBody> wildcard(@Body List<?> body);
@POST("/")
Call<ResponseBody> wildcardUpperBound(@Body List<? extends RequestBody> body);
}
interface VoidService {
@GET("/")
void nope();
}
interface Annotated {
@GET("/")
@Foo
Call<String> method();
@POST("/")
Call<ResponseBody> bodyParameter(@Foo @Body String param);
@GET("/")
Call<ResponseBody> queryParameter(@Foo @Query("foo") Object foo);
@Retention(RUNTIME)
@interface Foo {}
}
interface MutableParameters {
@GET("/")
Call<String> method(@Query("i") AtomicInteger value);
}
// We are explicitly testing this behavior.
@SuppressWarnings({"EqualsBetweenInconvertibleTypes", "EqualsIncompatibleType"})
@Test
public void objectMethodsStillWork() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
assertThat(example.hashCode()).isNotZero();
assertThat(example.equals(this)).isFalse();
assertThat(example.toString()).isNotEmpty();
}
@Test
public void interfaceWithTypeParameterThrows() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
server.enqueue(new MockResponse().setBody("Hi"));
try {
retrofit.create(TypeParam.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Type parameters are unsupported on retrofit2.RetrofitTest$TypeParam");
}
}
@Test
public void interfaceWithExtend() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
server.enqueue(new MockResponse().setBody("Hi"));
Extending extending = retrofit.create(Extending.class);
String result = extending.getResponseBody().execute().body().string();
assertEquals("Hi", result);
}
@Test
public void interfaceWithExtendWithTypeParameterThrows() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
server.enqueue(new MockResponse().setBody("Hi"));
try {
retrofit.create(ExtendingTypeParam.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Type parameters are unsupported on retrofit2.RetrofitTest$TypeParam "
+ "which is an interface of retrofit2.RetrofitTest$ExtendingTypeParam");
}
}
@Test
public void cloneSharesStatefulInstances() {
CallAdapter.Factory callAdapter =
new CallAdapter.Factory() {
@Nullable
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
throw new AssertionError();
}
};
Converter.Factory converter = new Converter.Factory() {};
HttpUrl baseUrl = server.url("/");
Executor executor = Runnable::run;
okhttp3.Call.Factory callFactory =
request -> {
throw new AssertionError();
};
Retrofit one =
new Retrofit.Builder()
.addCallAdapterFactory(callAdapter)
.addConverterFactory(converter)
.baseUrl(baseUrl)
.callbackExecutor(executor)
.callFactory(callFactory)
.build();
CallAdapter.Factory callAdapter2 =
new CallAdapter.Factory() {
@Nullable
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
throw new AssertionError();
}
};
Converter.Factory converter2 = new Converter.Factory() {};
Retrofit two =
one.newBuilder()
.addCallAdapterFactory(callAdapter2)
.addConverterFactory(converter2)
.build();
assertEquals(one.callAdapterFactories().size() + 1, two.callAdapterFactories().size());
assertThat(two.callAdapterFactories()).contains(callAdapter, callAdapter2);
assertEquals(one.converterFactories().size() + 1, two.converterFactories().size());
assertThat(two.converterFactories()).contains(converter, converter2);
assertSame(baseUrl, two.baseUrl());
assertSame(executor, two.callbackExecutor());
assertSame(callFactory, two.callFactory());
}
@Test
public void builtInConvertersAbsentInCloneBuilder() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
assertEquals(0, retrofit.newBuilder().converterFactories().size());
}
@Test
public void responseTypeCannotBeRetrofitResponse() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod service = retrofit.create(CallMethod.class);
try {
service.badType1();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Response must include generic type (e.g., Response<String>)\n"
+ " for method CallMethod.badType1");
}
}
@Test
public void responseTypeCannotBeOkHttpResponse() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod service = retrofit.create(CallMethod.class);
try {
service.badType2();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"'okhttp3.Response' is not a valid response body type. Did you mean ResponseBody?\n"
+ " for method CallMethod.badType2");
}
}
@Test
public void voidReturnTypeNotAllowed() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
VoidService service = retrofit.create(VoidService.class);
try {
service.nope();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageStartingWith(
"Service methods cannot return void.\n for method VoidService.nope");
}
}
@Test
public void validateEagerlyDisabledByDefault() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
// Should not throw exception about incorrect configuration of the VoidService
retrofit.create(VoidService.class);
}
@Test
public void validateEagerlyDisabledByUser() {
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).validateEagerly(false).build();
// Should not throw exception about incorrect configuration of the VoidService
retrofit.create(VoidService.class);
}
@Test
public void validateEagerlyFailsAtCreation() {
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).validateEagerly(true).build();
try {
retrofit.create(VoidService.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageStartingWith(
"Service methods cannot return void.\n for method VoidService.nope");
}
}
@Test
public void callCallAdapterAddedByDefault() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
assertThat(example.getResponseBody()).isNotNull();
}
@Test
public void callCallCustomAdapter() {
final AtomicBoolean factoryCalled = new AtomicBoolean();
final AtomicBoolean adapterCalled = new AtomicBoolean();
class MyCallAdapterFactory extends CallAdapter.Factory {
@Override
public @Nullable CallAdapter<?, ?> get(
final Type returnType, Annotation[] annotations, Retrofit retrofit) {
factoryCalled.set(true);
if (getRawType(returnType) != Call.class) {
return null;
}
return new CallAdapter<Object, Call<?>>() {
@Override
public Type responseType() {
return getParameterUpperBound(0, (ParameterizedType) returnType);
}
@Override
public Call<Object> adapt(Call<Object> call) {
adapterCalled.set(true);
return call;
}
};
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addCallAdapterFactory(new MyCallAdapterFactory())
.build();
CallMethod example = retrofit.create(CallMethod.class);
assertThat(example.getResponseBody()).isNotNull();
assertThat(factoryCalled.get()).isTrue();
assertThat(adapterCalled.get()).isTrue();
}
@Test
public void customCallAdapter() {
class GreetingCallAdapterFactory extends CallAdapter.Factory {
@Override
public @Nullable CallAdapter<Object, String> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != String.class) {
return null;
}
return new CallAdapter<Object, String>() {
@Override
public Type responseType() {
return String.class;
}
@Override
public String adapt(Call<Object> call) {
return "Hi!";
}
};
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.addCallAdapterFactory(new GreetingCallAdapterFactory())
.build();
StringService example = retrofit.create(StringService.class);
assertThat(example.get()).isEqualTo("Hi!");
}
@Test
public void methodAnnotationsPassedToCallAdapter() {
final AtomicReference<Annotation[]> annotationsRef = new AtomicReference<>();
class MyCallAdapterFactory extends CallAdapter.Factory {
@Override
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
annotationsRef.set(annotations);
return null;
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.addCallAdapterFactory(new MyCallAdapterFactory())
.build();
Annotated annotated = retrofit.create(Annotated.class);
annotated.method(); // Trigger internal setup.
Annotation[] annotations = annotationsRef.get();
assertThat(annotations).hasAtLeastOneElementOfType(Annotated.Foo.class);
}
@Test
public void customCallAdapterMissingThrows() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
FutureMethod example = retrofit.create(FutureMethod.class);
try {
example.method();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Unable to create call adapter for java.util.concurrent.Future<java.lang.String>\n"
+ " for method FutureMethod.method");
assertThat(e.getCause())
.hasMessage(
""
+ "Could not locate call adapter for java.util.concurrent.Future<java.lang.String>.\n"
+ " Tried:\n"
+ " * retrofit2.CompletableFutureCallAdapterFactory\n"
+ " * retrofit2.DefaultCallAdapterFactory");
}
}
@Test
public void methodAnnotationsPassedToResponseBodyConverter() {
final AtomicReference<Annotation[]> annotationsRef = new AtomicReference<>();
class MyConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
annotationsRef.set(annotations);
return new ToStringConverterFactory().responseBodyConverter(type, annotations, retrofit);
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new MyConverterFactory())
.build();
Annotated annotated = retrofit.create(Annotated.class);
annotated.method(); // Trigger internal setup.
Annotation[] annotations = annotationsRef.get();
assertThat(annotations).hasAtLeastOneElementOfType(Annotated.Foo.class);
}
@Test
public void methodAndParameterAnnotationsPassedToRequestBodyConverter() {
final AtomicReference<Annotation[]> parameterAnnotationsRef = new AtomicReference<>();
final AtomicReference<Annotation[]> methodAnnotationsRef = new AtomicReference<>();
class MyConverterFactory extends Converter.Factory {
@Override
public Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
parameterAnnotationsRef.set(parameterAnnotations);
methodAnnotationsRef.set(methodAnnotations);
return new ToStringConverterFactory()
.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new MyConverterFactory())
.build();
Annotated annotated = retrofit.create(Annotated.class);
annotated.bodyParameter(null); // Trigger internal setup.
assertThat(parameterAnnotationsRef.get()).hasAtLeastOneElementOfType(Annotated.Foo.class);
assertThat(methodAnnotationsRef.get()).hasAtLeastOneElementOfType(POST.class);
}
@Test
public void parameterAnnotationsPassedToStringConverter() {
final AtomicReference<Annotation[]> annotationsRef = new AtomicReference<>();
class MyConverterFactory extends Converter.Factory {
@Override
public Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
annotationsRef.set(annotations);
return (Converter<Object, String>) String::valueOf;
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new MyConverterFactory())
.build();
Annotated annotated = retrofit.create(Annotated.class);
annotated.queryParameter(null); // Trigger internal setup.
Annotation[] annotations = annotationsRef.get();
assertThat(annotations).hasAtLeastOneElementOfType(Annotated.Foo.class);
}
@Test
public void stringConverterCalledForString() {
final AtomicBoolean factoryCalled = new AtomicBoolean();
class MyConverterFactory extends Converter.Factory {
@Override
public @Nullable Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
factoryCalled.set(true);
return null;
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new MyConverterFactory())
.build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.queryString(null);
assertThat(call).isNotNull();
assertThat(factoryCalled.get()).isTrue();
}
@Test
public void stringConverterReturningNullResultsInDefault() {
final AtomicBoolean factoryCalled = new AtomicBoolean();
class MyConverterFactory extends Converter.Factory {
@Override
public @Nullable Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
factoryCalled.set(true);
return null;
}
}
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new MyConverterFactory())
.build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.queryObject(null);
assertThat(call).isNotNull();
assertThat(factoryCalled.get()).isTrue();
}
@Test
public void missingConverterThrowsOnNonRequestBody() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
try {
example.disallowed("Hi!");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Unable to create @Body converter for class java.lang.String (parameter #1)\n"
+ " for method CallMethod.disallowed");
assertThat(e.getCause())
.hasMessage(
""
+ "Could not locate RequestBody converter for class java.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.OptionalConverterFactory");
}
}
@Test
public void missingConverterThrowsOnNonResponseBody() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
server.enqueue(new MockResponse().setBody("Hi"));
try {
example.disallowed();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Unable to create converter for class java.lang.String\n"
+ " for method CallMethod.disallowed");
assertThat(e.getCause())
.hasMessage(
""
+ "Could not locate ResponseBody converter for class java.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.OptionalConverterFactory");
}
}
@Test
public void requestBodyOutgoingAllowed() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
server.enqueue(new MockResponse().setBody("Hi"));
Response<ResponseBody> response = example.getResponseBody().execute();
assertThat(response.body().string()).isEqualTo("Hi");
}
@Test
public void voidOutgoingAllowed() throws IOException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
server.enqueue(new MockResponse().setBody("Hi"));
Response<Void> response = example.getVoid().execute();
assertThat(response.body()).isNull();
}
@Test
public void voidResponsesArePooled() throws Exception {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
server.enqueue(new MockResponse().setBody("abc"));
server.enqueue(new MockResponse().setBody("def"));
example.getVoid().execute();
example.getVoid().execute();
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
}
@Test
public void responseBodyIncomingAllowed() throws IOException, InterruptedException {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
CallMethod example = retrofit.create(CallMethod.class);
server.enqueue(new MockResponse().setBody("Hi"));
RequestBody body = RequestBody.create(MediaType.get("text/plain"), "Hey");
Response<ResponseBody> response = example.postRequestBody(body).execute();
assertThat(response.body().string()).isEqualTo("Hi");
assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("Hey");
}
@Test
public void unresolvableResponseTypeThrows() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
UnresolvableResponseType example = retrofit.create(UnresolvableResponseType.class);
try {
example.typeVariable();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Method return type must not include a type variable or wildcard: "
+ "retrofit2.Call<T>\n for method UnresolvableResponseType.typeVariable");
}
try {
example.typeVariableUpperBound();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Method return type must not include a type variable or wildcard: "
+ "retrofit2.Call<T>\n for method UnresolvableResponseType.typeVariableUpperBound");
}
try {
example.crazy();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Method return type must not include a type variable or wildcard: "
+ "retrofit2.Call<java.util.List<java.util.Map<java.lang.String, java.util.Set<T[]>>>>\n"
+ " for method UnresolvableResponseType.crazy");
}
try {
example.wildcard();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Method return type must not include a type variable or wildcard: "
+ "retrofit2.Call<?>\n for method UnresolvableResponseType.wildcard");
}
try {
example.wildcardUpperBound();
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Method return type must not include a type variable or wildcard: "
+ "retrofit2.Call<? extends okhttp3.ResponseBody>\n"
+ " for method UnresolvableResponseType.wildcardUpperBound");
}
}
@Test
public void unresolvableParameterTypeThrows() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
UnresolvableParameterType example = retrofit.create(UnresolvableParameterType.class);
try {
example.typeVariable(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Parameter type must not include a type variable or wildcard: "
+ "T (parameter #1)\n for method UnresolvableParameterType.typeVariable");
}
try {
example.typeVariableUpperBound(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Parameter type must not include a type variable or wildcard: "
+ "T (parameter #1)\n for method UnresolvableParameterType.typeVariableUpperBound");
}
try {
example.crazy(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Parameter type must not include a type variable or wildcard: "
+ "java.util.List<java.util.Map<java.lang.String, java.util.Set<T[]>>> (parameter #1)\n"
+ " for method UnresolvableParameterType.crazy");
}
try {
example.wildcard(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Parameter type must not include a type variable or wildcard: "
+ "java.util.List<?> (parameter #1)\n for method UnresolvableParameterType.wildcard");
}
try {
example.wildcardUpperBound(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Parameter type must not include a type variable or wildcard: "
+ "java.util.List<? extends okhttp3.RequestBody> (parameter #1)\n"
+ " for method UnresolvableParameterType.wildcardUpperBound");
}
}
@Test
public void baseUrlRequired() {
try {
new Retrofit.Builder().build();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Base URL required.");
}
}
@Test
public void baseUrlNullThrows() {
try {
new Retrofit.Builder().baseUrl((String) null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("baseUrl == null");
}
try {
new Retrofit.Builder().baseUrl((HttpUrl) null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("baseUrl == null");
}
}
@Test
public void baseUrlInvalidThrows() {
try {
new Retrofit.Builder().baseUrl("ftp://foo/bar");
fail();
} catch (IllegalArgumentException ignored) {
}
}
@Test
public void baseUrlNoTrailingSlashThrows() {
try {
new Retrofit.Builder().baseUrl("http://example.com/api");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("baseUrl must end in /: http://example.com/api");
}
HttpUrl parsed = HttpUrl.get("http://example.com/api");
try {
new Retrofit.Builder().baseUrl(parsed);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("baseUrl must end in /: http://example.com/api");
}
}
@Test
public void baseUrlStringPropagated() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").build();
HttpUrl baseUrl = retrofit.baseUrl();
assertThat(baseUrl).isEqualTo(HttpUrl.get("http://example.com/"));
}
@Test
public void baseHttpUrlPropagated() {
HttpUrl url = HttpUrl.get("http://example.com/");
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).build();
assertThat(retrofit.baseUrl()).isSameAs(url);
}
@Test
public void baseJavaUrlPropagated() throws MalformedURLException {
URL url = new URL("http://example.com/");
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).build();
assertThat(retrofit.baseUrl()).isEqualTo(HttpUrl.get("http://example.com/"));
}
@Test
public void clientNullThrows() {
try {
new Retrofit.Builder().client(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("client == null");
}
}
@Test
public void callFactoryDefault() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com").build();
assertThat(retrofit.callFactory()).isNotNull();
}
@Test
public void callFactoryPropagated() {
okhttp3.Call.Factory callFactory =
request -> {
throw new AssertionError();
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").callFactory(callFactory).build();
assertThat(retrofit.callFactory()).isSameAs(callFactory);
}
@Test
public void callFactoryClientPropagated() {
OkHttpClient client = new OkHttpClient();
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").client(client).build();
assertThat(retrofit.callFactory()).isSameAs(client);
}
@Test
public void callFactoryUsed() throws IOException {
final AtomicBoolean called = new AtomicBoolean();
okhttp3.Call.Factory callFactory =
request -> {
called.set(true);
return new OkHttpClient().newCall(request);
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).callFactory(callFactory).build();
server.enqueue(new MockResponse());
CallMethod service = retrofit.create(CallMethod.class);
service.getResponseBody().execute();
assertTrue(called.get());
}
@Test
public void callFactoryReturningNullThrows() throws IOException {
okhttp3.Call.Factory callFactory = request -> null;
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").callFactory(callFactory).build();
server.enqueue(new MockResponse());
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBody();
try {
call.execute();
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("Call.Factory returned null.");
}
}
@Test
public void callFactoryThrowingPropagates() {
final RuntimeException cause = new RuntimeException("Broken!");
okhttp3.Call.Factory callFactory =
request -> {
throw cause;
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").callFactory(callFactory).build();
server.enqueue(new MockResponse());
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBody();
try {
call.execute();
fail();
} catch (Exception e) {
assertThat(e).isSameAs(cause);
}
}
@Test
public void converterNullThrows() {
try {
new Retrofit.Builder().addConverterFactory(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("factory == null");
}
}
@Test
public void converterFactoryDefault() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").build();
List<Converter.Factory> converterFactories = retrofit.converterFactories();
assertThat(converterFactories).hasSize(2);
assertThat(converterFactories.get(0)).isInstanceOf(BuiltInConverters.class);
}
@Test
public void builtInConvertersFirstInClone() {
Converter.Factory factory =
new Converter.Factory() {
@Nullable
@Override
public Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
throw new AssertionError(
"User converter factory shouldn't be called for built-in types");
}
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(factory)
.build()
.newBuilder() // Do a newBuilder().builder() dance to force the internal list to clone.
.build();
assertNotNull(retrofit.responseBodyConverter(Void.class, new Annotation[0]));
}
@Test
public void requestConverterFactoryQueried() {
final Converter<?, RequestBody> expectedAdapter =
new Converter<Object, RequestBody>() {
@Nullable
@Override
public RequestBody convert(Object value) {
throw new AssertionError();
}
};
Converter.Factory factory =
new Converter.Factory() {
@Override
public Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
return String.class.equals(type) ? expectedAdapter : null;
}
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(factory).build();
Converter<?, RequestBody> actualAdapter =
retrofit.requestBodyConverter(String.class, new Annotation[0], new Annotation[0]);
assertThat(actualAdapter).isSameAs(expectedAdapter);
}
@Test
public void requestConverterFactoryNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingConverterFactory nonMatchingFactory = new NonMatchingConverterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(nonMatchingFactory)
.build();
try {
retrofit.requestBodyConverter(type, annotations, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate RequestBody converter for class java.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " * retrofit2.OptionalConverterFactory");
}
assertThat(nonMatchingFactory.called).isTrue();
}
@Test
public void requestConverterFactorySkippedNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory();
NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(nonMatchingFactory1)
.addConverterFactory(nonMatchingFactory2)
.build();
try {
retrofit.nextRequestBodyConverter(nonMatchingFactory1, type, annotations, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate RequestBody converter for class java.lang.String.\n"
+ " Skipped:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " Tried:\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " * retrofit2.OptionalConverterFactory");
}
assertThat(nonMatchingFactory1.called).isFalse();
assertThat(nonMatchingFactory2.called).isTrue();
}
@Test
public void responseConverterFactoryQueried() {
final Converter<ResponseBody, ?> expectedAdapter =
new Converter<ResponseBody, Object>() {
@Nullable
@Override
public Object convert(ResponseBody value) {
throw new AssertionError();
}
};
Converter.Factory factory =
new Converter.Factory() {
@Nullable
@Override
public Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return String.class.equals(type) ? expectedAdapter : null;
}
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(factory).build();
Converter<ResponseBody, ?> actualAdapter =
retrofit.responseBodyConverter(String.class, new Annotation[0]);
assertThat(actualAdapter).isSameAs(expectedAdapter);
}
@Test
public void responseConverterFactoryNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingConverterFactory nonMatchingFactory = new NonMatchingConverterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(nonMatchingFactory)
.build();
try {
retrofit.responseBodyConverter(type, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate ResponseBody converter for class java.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " * retrofit2.OptionalConverterFactory");
}
assertThat(nonMatchingFactory.called).isTrue();
}
@Test
public void responseConverterFactorySkippedNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory();
NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addConverterFactory(nonMatchingFactory1)
.addConverterFactory(nonMatchingFactory2)
.build();
try {
retrofit.nextResponseBodyConverter(nonMatchingFactory1, type, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate ResponseBody converter for class java.lang.String.\n"
+ " Skipped:\n"
+ " * retrofit2.BuiltInConverters\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " Tried:\n"
+ " * retrofit2.helpers.NonMatchingConverterFactory\n"
+ " * retrofit2.OptionalConverterFactory");
}
assertThat(nonMatchingFactory1.called).isFalse();
assertThat(nonMatchingFactory2.called).isTrue();
}
@Test
public void stringConverterFactoryQueried() {
final Converter<?, String> expectedConverter =
new Converter<Object, String>() {
@Nullable
@Override
public String convert(Object value) {
throw new AssertionError();
}
};
Converter.Factory factory =
new Converter.Factory() {
@Nullable
@Override
public Converter<?, String> stringConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return Object.class.equals(type) ? expectedConverter : null;
}
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(factory).build();
Converter<?, String> actualConverter =
retrofit.stringConverter(Object.class, new Annotation[0]);
assertThat(actualConverter).isSameAs(expectedConverter);
}
@Test
public void converterFactoryPropagated() {
Converter.Factory factory = new Converter.Factory() {};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(factory).build();
assertThat(retrofit.converterFactories()).contains(factory);
}
@Test
public void callAdapterFactoryNullThrows() {
try {
new Retrofit.Builder().addCallAdapterFactory(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("factory == null");
}
}
@Test
public void callAdapterFactoryDefault() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").build();
assertThat(retrofit.callAdapterFactories()).isNotEmpty();
}
@Test
public void callAdapterFactoryPropagated() {
CallAdapter.Factory factory =
new CallAdapter.Factory() {
@Nullable
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
throw new AssertionError();
}
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(factory)
.build();
assertThat(retrofit.callAdapterFactories()).contains(factory);
}
@Test
public void callAdapterFactoryQueried() {
final CallAdapter<?, ?> expectedAdapter =
new CallAdapter<Object, Object>() {
@Override
public Type responseType() {
throw new AssertionError();
}
@Override
public Object adapt(Call<Object> call) {
throw new AssertionError();
}
};
CallAdapter.Factory factory =
new CallAdapter.Factory() {
@Nullable
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
return String.class.equals(returnType) ? expectedAdapter : null;
}
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(factory)
.build();
CallAdapter<?, ?> actualAdapter = retrofit.callAdapter(String.class, new Annotation[0]);
assertThat(actualAdapter).isSameAs(expectedAdapter);
}
@Test
public void callAdapterFactoryQueriedCanDelegate() {
final CallAdapter<?, ?> expectedAdapter =
new CallAdapter<Object, Object>() {
@Override
public Type responseType() {
throw new AssertionError();
}
@Override
public Object adapt(Call<Object> call) {
throw new AssertionError();
}
};
CallAdapter.Factory factory2 =
new CallAdapter.Factory() {
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
return expectedAdapter;
}
};
final AtomicBoolean factory1called = new AtomicBoolean();
CallAdapter.Factory factory1 =
new CallAdapter.Factory() {
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
factory1called.set(true);
return retrofit.nextCallAdapter(this, returnType, annotations);
}
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(factory1)
.addCallAdapterFactory(factory2)
.build();
CallAdapter<?, ?> actualAdapter = retrofit.callAdapter(String.class, new Annotation[0]);
assertThat(actualAdapter).isSameAs(expectedAdapter);
assertTrue(factory1called.get());
}
@Test
public void callAdapterFactoryQueriedCanDelegateTwiceWithoutRecursion() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
final CallAdapter<?, ?> expectedAdapter =
new CallAdapter<Object, Object>() {
@Override
public Type responseType() {
throw new AssertionError();
}
@Override
public Object adapt(Call<Object> call) {
throw new AssertionError();
}
};
CallAdapter.Factory factory3 =
new CallAdapter.Factory() {
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
return expectedAdapter;
}
};
final AtomicBoolean factory2called = new AtomicBoolean();
CallAdapter.Factory factory2 =
new CallAdapter.Factory() {
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
factory2called.set(true);
return retrofit.nextCallAdapter(this, returnType, annotations);
}
};
final AtomicBoolean factory1called = new AtomicBoolean();
CallAdapter.Factory factory1 =
new CallAdapter.Factory() {
@Override
public CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
factory1called.set(true);
return retrofit.nextCallAdapter(this, returnType, annotations);
}
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(factory1)
.addCallAdapterFactory(factory2)
.addCallAdapterFactory(factory3)
.build();
CallAdapter<?, ?> actualAdapter = retrofit.callAdapter(type, annotations);
assertThat(actualAdapter).isSameAs(expectedAdapter);
assertTrue(factory1called.get());
assertTrue(factory2called.get());
}
@Test
public void callAdapterFactoryNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(nonMatchingFactory)
.build();
try {
retrofit.callAdapter(type, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate call adapter for class java.lang.String.\n"
+ " Tried:\n"
+ " * retrofit2.helpers.NonMatchingCallAdapterFactory\n"
+ " * retrofit2.CompletableFutureCallAdapterFactory\n"
+ " * retrofit2.DefaultCallAdapterFactory");
}
assertThat(nonMatchingFactory.called).isTrue();
}
@Test
public void callAdapterFactoryDelegateNoMatchThrows() {
Type type = String.class;
Annotation[] annotations = new Annotation[0];
DelegatingCallAdapterFactory delegatingFactory1 = new DelegatingCallAdapterFactory();
DelegatingCallAdapterFactory delegatingFactory2 = new DelegatingCallAdapterFactory();
NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.addCallAdapterFactory(delegatingFactory1)
.addCallAdapterFactory(delegatingFactory2)
.addCallAdapterFactory(nonMatchingFactory)
.build();
try {
retrofit.callAdapter(type, annotations);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
""
+ "Could not locate call adapter for class java.lang.String.\n"
+ " Skipped:\n"
+ " * retrofit2.helpers.DelegatingCallAdapterFactory\n"
+ " * retrofit2.helpers.DelegatingCallAdapterFactory\n"
+ " Tried:\n"
+ " * retrofit2.helpers.NonMatchingCallAdapterFactory\n"
+ " * retrofit2.CompletableFutureCallAdapterFactory\n"
+ " * retrofit2.DefaultCallAdapterFactory");
}
assertThat(delegatingFactory1.called).isTrue();
assertThat(delegatingFactory2.called).isTrue();
assertThat(nonMatchingFactory.called).isTrue();
}
@Test
public void platformAwareAdapterAbsentInCloneBuilder() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).build();
assertEquals(0, retrofit.newBuilder().callAdapterFactories().size());
}
@Test
public void callbackExecutorNullThrows() {
try {
new Retrofit.Builder().callbackExecutor(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("executor == null");
}
}
@Test
public void callbackExecutorPropagated() {
Executor executor =
command -> {
throw new AssertionError();
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl("http://example.com/").callbackExecutor(executor).build();
assertThat(retrofit.callbackExecutor()).isSameAs(executor);
}
@Test
public void callbackExecutorUsedForSuccess() throws InterruptedException {
final CountDownLatch runnableLatch = new CountDownLatch(1);
final AtomicReference<Runnable> runnableRef = new AtomicReference<>();
Executor executor =
command -> {
runnableRef.set(command);
runnableLatch.countDown();
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).callbackExecutor(executor).build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBody();
server.enqueue(new MockResponse());
final CountDownLatch callbackLatch = new CountDownLatch(1);
call.enqueue(
new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
callbackLatch.countDown();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
assertTrue(runnableLatch.await(2, TimeUnit.SECONDS));
assertEquals(1, callbackLatch.getCount()); // Callback not run yet.
runnableRef.get().run();
assertTrue(callbackLatch.await(2, TimeUnit.SECONDS));
}
@Test
public void callbackExecutorUsedForFailure() throws InterruptedException {
final CountDownLatch runnableLatch = new CountDownLatch(1);
final AtomicReference<Runnable> runnableRef = new AtomicReference<>();
Executor executor =
command -> {
runnableRef.set(command);
runnableLatch.countDown();
};
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).callbackExecutor(executor).build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBody();
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
final CountDownLatch callbackLatch = new CountDownLatch(1);
call.enqueue(
new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callbackLatch.countDown();
}
});
assertTrue(runnableLatch.await(2, TimeUnit.SECONDS));
assertEquals(1, callbackLatch.getCount()); // Callback not run yet.
runnableRef.get().run();
assertTrue(callbackLatch.await(2, TimeUnit.SECONDS));
}
@Test
public void skippedCallbackExecutorNotUsedForSuccess() throws InterruptedException {
Executor executor = command -> fail();
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).callbackExecutor(executor).build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBodySkippedExecutor();
server.enqueue(new MockResponse());
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
latch.countDown();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
assertTrue(latch.await(2, TimeUnit.SECONDS));
}
@Test
public void skippedCallbackExecutorNotUsedForFailure() throws InterruptedException {
Executor executor = command -> fail();
Retrofit retrofit =
new Retrofit.Builder().baseUrl(server.url("/")).callbackExecutor(executor).build();
CallMethod service = retrofit.create(CallMethod.class);
Call<ResponseBody> call = service.getResponseBodySkippedExecutor();
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AT_START));
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
latch.countDown();
}
});
assertTrue(latch.await(2, TimeUnit.SECONDS));
}
/** Confirm that Retrofit encodes parameters when the call is executed, and not earlier. */
@Test
public void argumentCapture() throws Exception {
AtomicInteger i = new AtomicInteger();
server.enqueue(new MockResponse().setBody("a"));
server.enqueue(new MockResponse().setBody("b"));
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
MutableParameters mutableParameters = retrofit.create(MutableParameters.class);
i.set(100);
Call<String> call1 = mutableParameters.method(i);
i.set(101);
Response<String> response1 = call1.execute();
i.set(102);
assertEquals("a", response1.body());
assertEquals("/?i=101", server.takeRequest().getPath());
i.set(200);
Call<String> call2 = call1.clone();
i.set(201);
Response<String> response2 = call2.execute();
i.set(202);
assertEquals("b", response2.body());
assertEquals("/?i=201", server.takeRequest().getPath());
}
}
| 3,686 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/HttpExceptionTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
public final class HttpExceptionTest {
@Test
public void response() {
Response<String> response = Response.success("Hi");
HttpException exception = new HttpException(response);
assertThat(exception.code()).isEqualTo(200);
assertThat(exception.message()).isEqualTo("OK");
assertThat(exception.response()).isSameAs(response);
}
@Test
public void nullResponseThrows() {
try {
new HttpException(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("response == null");
}
}
}
| 3,687 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/NonFatalError.java | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
final class NonFatalError extends Error {
NonFatalError(String message) {
super(message);
}
}
| 3,688 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/CallTest.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static java.util.concurrent.TimeUnit.SECONDS;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static retrofit2.TestingUtils.repeat;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Streaming;
public final class CallTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
Call<String> getString();
@GET("/")
Call<ResponseBody> getBody();
@GET("/")
@Streaming
Call<ResponseBody> getStreamingBody();
@POST("/")
Call<String> postString(@Body String body);
@POST("/{a}")
Call<String> postRequestBody(@Path("a") Object a);
}
@Test
public void http200Sync() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Response<String> response = example.getString().execute();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isEqualTo("Hi");
}
@Test
public void http200Async() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
final AtomicReference<Response<String>> responseRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
example
.getString()
.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
responseRef.set(response);
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
t.printStackTrace();
}
});
assertTrue(latch.await(10, SECONDS));
Response<String> response = responseRef.get();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isEqualTo("Hi");
}
@Test
public void http404Sync() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));
Response<String> response = example.getString().execute();
assertThat(response.isSuccessful()).isFalse();
assertThat(response.code()).isEqualTo(404);
assertThat(response.errorBody().string()).isEqualTo("Hi");
}
@Test
public void http404Async() throws InterruptedException, IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));
final AtomicReference<Response<String>> responseRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
example
.getString()
.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
responseRef.set(response);
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
t.printStackTrace();
}
});
assertTrue(latch.await(10, SECONDS));
Response<String> response = responseRef.get();
assertThat(response.isSuccessful()).isFalse();
assertThat(response.code()).isEqualTo(404);
assertThat(response.errorBody().string()).isEqualTo("Hi");
}
@Test
public void transportProblemSync() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
Call<String> call = example.getString();
try {
call.execute();
fail();
} catch (IOException ignored) {
}
}
@Test
public void transportProblemAsync() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
example
.getString()
.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
Throwable failure = failureRef.get();
assertThat(failure).isInstanceOf(IOException.class);
}
@Test
public void conversionProblemOutgoingSync() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<String, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
return value -> {
throw new UnsupportedOperationException("I am broken!");
};
}
})
.build();
Service example = retrofit.create(Service.class);
Call<String> call = example.postString("Hi");
try {
call.execute();
fail();
} catch (UnsupportedOperationException e) {
assertThat(e).hasMessage("I am broken!");
}
}
@Test
public void conversionProblemOutgoingAsync() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<String, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
return value -> {
throw new UnsupportedOperationException("I am broken!");
};
}
})
.build();
Service example = retrofit.create(Service.class);
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
example
.postString("Hi")
.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
assertThat(failureRef.get())
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("I am broken!");
}
@Test
public void conversionProblemIncomingSync() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
throw new UnsupportedOperationException("I am broken!");
};
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Call<String> call = example.postString("Hi");
try {
call.execute();
fail();
} catch (UnsupportedOperationException e) {
assertThat(e).hasMessage("I am broken!");
}
}
@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
// MWS has no way to trigger IOExceptions during the response body so use an interceptor.
OkHttpClient client =
new OkHttpClient.Builder() //
.addInterceptor(
chain -> {
okhttp3.Response response = chain.proceed(chain.request());
ResponseBody body = response.body();
BufferedSource source =
Okio.buffer(
new ForwardingSource(body.source()) {
@Override
public long read(Buffer sink, long byteCount) throws IOException {
throw new IOException("cause");
}
});
body = ResponseBody.create(body.contentType(), body.contentLength(), source);
return response.newBuilder().body(body).build();
})
.build();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.client(client)
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
try {
return value.string();
} catch (IOException e) {
// Some serialization libraries mask transport problems in runtime
// exceptions. Bad!
throw new RuntimeException("wrapper", e);
}
};
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Call<String> call = example.getString();
try {
call.execute();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("cause");
}
}
@Test
public void conversionProblemIncomingAsync() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
throw new UnsupportedOperationException("I am broken!");
};
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
example
.postString("Hi")
.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
assertThat(failureRef.get())
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("I am broken!");
}
@Test
public void http204SkipsConverter() throws IOException {
final Converter<ResponseBody, String> converter =
value -> {
throw new AssertionError();
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return converter;
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin"));
Response<String> response = example.getString().execute();
assertThat(response.code()).isEqualTo(204);
assertThat(response.body()).isNull();
}
@Test
public void http205SkipsConverter() throws IOException {
final Converter<ResponseBody, String> converter =
value -> {
throw new AssertionError();
};
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return converter;
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin"));
Response<String> response = example.getString().execute();
assertThat(response.code()).isEqualTo(205);
assertThat(response.body()).isNull();
}
@Test
public void converterBodyDoesNotLeakContentInIntermediateBuffers() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
new Converter.Factory() {
@Override
public Converter<ResponseBody, String> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
return value -> {
String prefix = value.source().readUtf8(2);
value.source().skip(20_000 - 4);
String suffix = value.source().readUtf8();
return prefix + suffix;
};
}
})
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody(repeat('a', 10_000) + repeat('b', 10_000)));
Response<String> response = example.getString().execute();
assertThat(response.body()).isEqualTo("aabb");
}
@Test
public void executeCallOnce() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse());
Call<String> call = example.getString();
call.execute();
try {
call.execute();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Already executed.");
}
}
@Test
public void successfulRequestResponseWhenMimeTypeMissing() throws Exception {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi").removeHeader("Content-Type"));
Response<String> response = example.getString().execute();
assertThat(response.body()).isEqualTo("Hi");
}
@Test
public void responseBody() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("1234"));
Response<ResponseBody> response = example.getBody().execute();
assertThat(response.body().string()).isEqualTo("1234");
}
@Test
public void responseBodyBuffers() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(
new MockResponse().setBody("1234").setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY));
Call<ResponseBody> buffered = example.getBody();
// When buffering we will detect all socket problems before returning the Response.
try {
buffered.execute();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("unexpected end of stream");
}
}
@Test
public void responseBodyStreams() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(
new MockResponse().setBody("1234").setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY));
Response<ResponseBody> response = example.getStreamingBody().execute();
ResponseBody streamedBody = response.body();
// When streaming we only detect socket problems as the ResponseBody is read.
try {
streamedBody.string();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("unexpected end of stream");
}
}
@Test
public void rawResponseContentTypeAndLengthButNoSource() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi").addHeader("Content-Type", "text/greeting"));
Response<String> response = example.getString().execute();
assertThat(response.body()).isEqualTo("Hi");
ResponseBody rawBody = response.raw().body();
assertThat(rawBody.contentLength()).isEqualTo(2);
assertThat(rawBody.contentType().toString()).isEqualTo("text/greeting");
try {
rawBody.source();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Cannot read raw response body of a converted body.");
}
}
@Test
public void emptyResponse() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("").addHeader("Content-Type", "text/stringy"));
Response<String> response = example.getString().execute();
assertThat(response.body()).isEqualTo("");
ResponseBody rawBody = response.raw().body();
assertThat(rawBody.contentLength()).isEqualTo(0);
assertThat(rawBody.contentType().toString()).isEqualTo("text/stringy");
}
@Test
public void reportsExecutedSync() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Call<String> call = example.getString();
assertThat(call.isExecuted()).isFalse();
call.execute();
assertThat(call.isExecuted()).isTrue();
}
@Test
public void reportsExecutedAsync() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Call<String> call = example.getString();
assertThat(call.isExecuted()).isFalse();
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {}
});
assertThat(call.isExecuted()).isTrue();
}
@Test
public void cancelBeforeExecute() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
Call<String> call = service.getString();
call.cancel();
assertThat(call.isCanceled()).isTrue();
try {
call.execute();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("Canceled");
}
}
@Test
public void cancelBeforeEnqueue() throws Exception {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
Call<String> call = service.getString();
call.cancel();
assertThat(call.isCanceled()).isTrue();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
assertThat(failureRef.get()).hasMessage("Canceled");
}
@Test
public void cloningExecutedRequestDoesNotCopyState() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
server.enqueue(new MockResponse().setBody("Hello"));
Call<String> call = service.getString();
assertThat(call.execute().body()).isEqualTo("Hi");
Call<String> cloned = call.clone();
assertThat(cloned.execute().body()).isEqualTo("Hello");
}
@Test
public void cancelRequest() throws InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
Call<String> call = service.getString();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
call.cancel();
assertThat(call.isCanceled()).isTrue();
assertTrue(latch.await(10, SECONDS));
assertThat(failureRef.get()).isInstanceOf(IOException.class).hasMessage("Canceled");
}
@Test
public void cancelOkHttpRequest() throws InterruptedException {
OkHttpClient client = new OkHttpClient();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.client(client)
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
Call<String> call = service.getString();
final AtomicReference<Throwable> failureRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
throw new AssertionError();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
// Cancel the underlying HTTP Call. Should be reflected accurately back in the Retrofit Call.
client.dispatcher().cancelAll();
assertThat(call.isCanceled()).isTrue();
assertTrue(latch.await(10, SECONDS));
assertThat(failureRef.get()).isInstanceOf(IOException.class).hasMessage("Canceled");
}
@Test
public void requestBeforeExecuteCreates() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
return "Hello";
}
};
Call<String> call = service.postRequestBody(a);
call.request();
assertThat(writeCount.get()).isEqualTo(1);
call.execute();
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestThrowingBeforeExecuteFailsExecute() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new RuntimeException("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.request();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.execute();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestThrowingNonFatalErrorBeforeExecuteFailsExecute() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new NonFatalError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.request();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.execute();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestAfterExecuteReturnsCachedValue() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
return "Hello";
}
};
Call<String> call = service.postRequestBody(a);
call.execute();
assertThat(writeCount.get()).isEqualTo(1);
call.request();
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestAfterExecuteThrowingAlsoThrows() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new RuntimeException("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.execute();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.request();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestAfterExecuteThrowingAlsoThrowsForNonFatalErrors() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new NonFatalError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.execute();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.request();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestBeforeEnqueueCreates() throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
return "Hello";
}
};
Call<String> call = service.postRequestBody(a);
call.request();
assertThat(writeCount.get()).isEqualTo(1);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {}
});
assertTrue(latch.await(10, SECONDS));
}
@Test
public void requestThrowingBeforeEnqueueFailsEnqueue() throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new RuntimeException("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.request();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {
assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!");
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
}
@Test
public void requestThrowingNonFatalErrorBeforeEnqueueFailsEnqueue()
throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new NonFatalError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.request();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {
assertThat(t).isExactlyInstanceOf(NonFatalError.class).hasMessage("Broken!");
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
}
@Test
public void requestAfterEnqueueReturnsCachedValue() throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
return "Hello";
}
};
Call<String> call = service.postRequestBody(a);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
@Override
public void onFailure(Call<String> call, Throwable t) {}
});
assertTrue(latch.await(10, SECONDS));
call.request();
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestAfterEnqueueFailingThrows() throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new RuntimeException("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {
assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!");
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
try {
call.request();
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void requestAfterEnqueueFailingThrowsForNonFatalErrors()
throws IOException, InterruptedException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new NonFatalError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
final CountDownLatch latch = new CountDownLatch(1);
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {
assertThat(t).isExactlyInstanceOf(NonFatalError.class).hasMessage("Broken!");
assertThat(writeCount.get()).isEqualTo(1);
latch.countDown();
}
});
assertTrue(latch.await(10, SECONDS));
try {
call.request();
fail();
} catch (NonFatalError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
@Test
public void fatalErrorsAreNotCaughtRequest() throws Exception {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new OutOfMemoryError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.request();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.request();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(2);
}
@Test
public void fatalErrorsAreNotCaughtEnqueue() throws Exception {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new OutOfMemoryError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
final AtomicBoolean callsFailureSynchronously = new AtomicBoolean();
call.enqueue(
new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {}
@Override
public void onFailure(Call<String> call, Throwable t) {
callsFailureSynchronously.set(true); // Will not be called for fatal errors.
}
});
assertThat(callsFailureSynchronously.get()).isFalse();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.request();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(2);
}
@Test
public void fatalErrorsAreNotCaughtExecute() throws Exception {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a =
new Object() {
@Override
public String toString() {
writeCount.incrementAndGet();
throw new OutOfMemoryError("Broken!");
}
};
Call<String> call = service.postRequestBody(a);
try {
call.execute();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
try {
call.request();
fail();
} catch (OutOfMemoryError e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(2);
}
@Test
public void timeoutExceeded() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setHeadersDelay(500, TimeUnit.MILLISECONDS));
Call<String> call = example.getString();
call.timeout().timeout(100, TimeUnit.MILLISECONDS);
try {
call.execute();
fail();
} catch (InterruptedIOException expected) {
}
}
@Test
public void deadlineExceeded() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setHeadersDelay(500, TimeUnit.MILLISECONDS));
Call<String> call = example.getString();
call.timeout().deadline(100, TimeUnit.MILLISECONDS);
try {
call.execute();
fail();
} catch (InterruptedIOException expected) {
}
}
@Test
public void timeoutEnabledButNotExceeded() throws IOException {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setHeadersDelay(100, TimeUnit.MILLISECONDS));
Call<String> call = example.getString();
call.timeout().deadline(500, TimeUnit.MILLISECONDS);
Response<String> response = call.execute();
assertThat(response.isSuccessful()).isTrue();
}
}
| 3,689 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/CallAdapterTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static retrofit2.CallAdapter.Factory.getParameterUpperBound;
import static retrofit2.CallAdapter.Factory.getRawType;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public final class CallAdapterTest {
@Test
public void parameterizedTypeInvalidIndex() {
ParameterizedType listOfString = (ParameterizedType) new TypeToken<List<String>>() {}.getType();
try {
getParameterUpperBound(-1, listOfString);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Index -1 not in range [0,1) for java.util.List<java.lang.String>");
}
try {
getParameterUpperBound(1, listOfString);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Index 1 not in range [0,1) for java.util.List<java.lang.String>");
}
}
@Test
public void parameterizedTypes() {
ParameterizedType one = (ParameterizedType) new TypeToken<List<String>>() {}.getType();
assertThat(getParameterUpperBound(0, one)).isSameAs(String.class);
ParameterizedType two = (ParameterizedType) new TypeToken<Map<String, String>>() {}.getType();
assertThat(getParameterUpperBound(0, two)).isSameAs(String.class);
assertThat(getParameterUpperBound(1, two)).isSameAs(String.class);
ParameterizedType wild =
(ParameterizedType) new TypeToken<List<? extends CharSequence>>() {}.getType();
assertThat(getParameterUpperBound(0, wild)).isSameAs(CharSequence.class);
}
@Test
public void rawTypeThrowsOnNull() {
try {
getRawType(null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("type == null");
}
}
@Test
public void rawTypes() throws NoSuchMethodException {
assertThat(getRawType(String.class)).isSameAs(String.class);
Type listOfString = new TypeToken<List<String>>() {}.getType();
assertThat(getRawType(listOfString)).isSameAs(List.class);
Type stringArray = new TypeToken<String[]>() {}.getType();
assertThat(getRawType(stringArray)).isSameAs(String[].class);
Type wild =
((ParameterizedType) new TypeToken<List<? extends CharSequence>>() {}.getType())
.getActualTypeArguments()[0];
assertThat(getRawType(wild)).isSameAs(CharSequence.class);
Type wildParam =
((ParameterizedType) new TypeToken<List<? extends List<String>>>() {}.getType())
.getActualTypeArguments()[0];
assertThat(getRawType(wildParam)).isSameAs(List.class);
Type typeVar = A.class.getDeclaredMethod("method").getGenericReturnType();
assertThat(getRawType(typeVar)).isSameAs(Object.class);
}
@SuppressWarnings("unused") // Used reflectively.
static class A<T> {
T method() {
return null;
}
}
}
| 3,690 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/DefaultCallAdapterFactoryTest.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.reflect.TypeToken;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import okhttp3.Request;
import okio.Timeout;
import org.junit.Test;
@SuppressWarnings("unchecked")
public final class DefaultCallAdapterFactoryTest {
private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
private final Retrofit retrofit = new Retrofit.Builder().baseUrl("http://localhost:1").build();
private final CallAdapter.Factory factory = new DefaultCallAdapterFactory(Runnable::run);
@Test
public void rawTypeThrows() {
try {
factory.get(Call.class, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
}
@Test
public void responseType() {
Type classType = new TypeToken<Call<String>>() {}.getType();
assertThat(factory.get(classType, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type wilcardType = new TypeToken<Call<? extends String>>() {}.getType();
assertThat(factory.get(wilcardType, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type genericType = new TypeToken<Call<List<String>>>() {}.getType();
assertThat(factory.get(genericType, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
}
@Test
public void adaptedCallExecute() throws IOException {
Type returnType = new TypeToken<Call<String>>() {}.getType();
CallAdapter<String, Call<String>> adapter =
(CallAdapter<String, Call<String>>) factory.get(returnType, NO_ANNOTATIONS, retrofit);
final Response<String> response = Response.success("Hi");
Call<String> call =
adapter.adapt(
new EmptyCall() {
@Override
public Response<String> execute() {
return response;
}
});
assertThat(call.execute()).isSameAs(response);
}
@Test
public void adaptedCallCloneDeepCopy() {
Type returnType = new TypeToken<Call<String>>() {}.getType();
CallAdapter<String, Call<String>> adapter =
(CallAdapter<String, Call<String>>) factory.get(returnType, NO_ANNOTATIONS, retrofit);
final AtomicBoolean cloned = new AtomicBoolean();
Call<String> delegate =
new EmptyCall() {
@Override
public Call<String> clone() {
cloned.set(true);
return this;
}
};
Call<String> call = adapter.adapt(delegate);
assertThat(call.clone()).isNotSameAs(call);
assertTrue(cloned.get());
}
@Test
public void adaptedCallCancel() {
Type returnType = new TypeToken<Call<String>>() {}.getType();
CallAdapter<String, Call<String>> adapter =
(CallAdapter<String, Call<String>>) factory.get(returnType, NO_ANNOTATIONS, retrofit);
final AtomicBoolean canceled = new AtomicBoolean();
Call<String> delegate =
new EmptyCall() {
@Override
public void cancel() {
canceled.set(true);
}
};
Call<String> call = adapter.adapt(delegate);
call.cancel();
assertTrue(canceled.get());
}
static class EmptyCall implements Call<String> {
@Override
public void enqueue(Callback<String> callback) {
throw new UnsupportedOperationException();
}
@Override
public boolean isExecuted() {
return false;
}
@Override
public Response<String> execute() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void cancel() {
throw new UnsupportedOperationException();
}
@Override
public boolean isCanceled() {
return false;
}
@Override
public Call<String> clone() {
throw new UnsupportedOperationException();
}
@Override
public Request request() {
throw new UnsupportedOperationException();
}
@Override
public Timeout timeout() {
return Timeout.NONE;
}
}
}
| 3,691 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/CompletableFutureTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.GET;
public final class CompletableFutureTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/")
CompletableFuture<String> body();
@GET("/")
CompletableFuture<Response<String>> response();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodySuccess200() throws Exception {
server.enqueue(new MockResponse().setBody("Hi"));
CompletableFuture<String> future = service.body();
assertThat(future.get()).isEqualTo("Hi");
}
@Test
public void bodySuccess404() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404));
CompletableFuture<String> future = service.body();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause())
.isInstanceOf(HttpException.class) // Required for backwards compatibility.
.isInstanceOf(HttpException.class)
.hasMessage("HTTP 404 Client Error");
}
}
@Test
public void bodyFailure() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
CompletableFuture<String> future = service.body();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(IOException.class);
}
}
@Test
public void responseSuccess200() throws Exception {
server.enqueue(new MockResponse().setBody("Hi"));
CompletableFuture<Response<String>> future = service.response();
Response<String> response = future.get();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isEqualTo("Hi");
}
@Test
public void responseSuccess404() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404).setBody("Hi"));
CompletableFuture<Response<String>> future = service.response();
Response<String> response = future.get();
assertThat(response.isSuccessful()).isFalse();
assertThat(response.errorBody().string()).isEqualTo("Hi");
}
@Test
public void responseFailure() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
CompletableFuture<Response<String>> future = service.response();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(IOException.class);
}
}
}
| 3,692 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/RequestFactoryBuilderTest.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import org.junit.Test;
// TODO this test is far too white box, migrate to black box.
public final class RequestFactoryBuilderTest {
@Test
public void pathParameterParsing() throws Exception {
expectParams("/");
expectParams("/foo");
expectParams("/foo/bar");
expectParams("/foo/bar/{}");
expectParams("/foo/bar/{taco}", "taco");
expectParams("/foo/bar/{t}", "t");
expectParams("/foo/bar/{!!!}/"); // Invalid parameter.
expectParams("/foo/bar/{}/{taco}", "taco");
expectParams("/foo/bar/{taco}/or/{burrito}", "taco", "burrito");
expectParams("/foo/bar/{taco}/or/{taco}", "taco");
expectParams("/foo/bar/{taco-shell}", "taco-shell");
expectParams("/foo/bar/{taco_shell}", "taco_shell");
expectParams("/foo/bar/{sha256}", "sha256");
expectParams("/foo/bar/{TACO}", "TACO");
expectParams("/foo/bar/{taco}/{tAco}/{taCo}", "taco", "tAco", "taCo");
expectParams("/foo/bar/{1}"); // Invalid parameter, name cannot start with digit.
}
private static void expectParams(String path, String... expected) {
Set<String> calculated = RequestFactory.Builder.parsePathParameters(path);
assertThat(calculated).containsExactly(expected);
}
}
| 3,693 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/Java8DefaultStaticMethodsInValidationTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.junit.Assert.assertNotNull;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
public final class Java8DefaultStaticMethodsInValidationTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Example {
@GET("/")
Call<String> user(@Query("name") String name);
default Call<String> user() {
return user("hey");
}
static String staticMethod() {
return "Hi";
}
}
@Test
public void test() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.validateEagerly(true)
.build();
assertNotNull(retrofit.create(Example.class));
}
}
| 3,694 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/ResponseTest.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.ResponseBody;
import org.junit.Test;
public final class ResponseTest {
private final okhttp3.Response successResponse =
new okhttp3.Response.Builder() //
.code(200)
.message("OK")
.protocol(Protocol.HTTP_1_1)
.request(new okhttp3.Request.Builder().url("http://localhost").build())
.build();
private final okhttp3.Response errorResponse =
new okhttp3.Response.Builder() //
.code(400)
.message("Broken!")
.protocol(Protocol.HTTP_1_1)
.request(new okhttp3.Request.Builder().url("http://localhost").build())
.build();
@Test
public void success() {
Object body = new Object();
Response<Object> response = Response.success(body);
assertThat(response.raw()).isNotNull();
assertThat(response.code()).isEqualTo(200);
assertThat(response.message()).isEqualTo("OK");
assertThat(response.headers().size()).isZero();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(body);
assertThat(response.errorBody()).isNull();
}
@Test
public void successNullAllowed() {
Response<Object> response = Response.success(null);
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isNull();
}
@Test
public void successWithHeaders() {
Object body = new Object();
Headers headers = Headers.of("foo", "bar");
Response<Object> response = Response.success(body, headers);
assertThat(response.raw()).isNotNull();
assertThat(response.code()).isEqualTo(200);
assertThat(response.message()).isEqualTo("OK");
assertThat(response.headers().toMultimap()).isEqualTo(headers.toMultimap());
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(body);
assertThat(response.errorBody()).isNull();
}
@Test
public void successWithNullHeadersThrows() {
try {
Response.success("", (okhttp3.Headers) null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("headers == null");
}
}
@Test
public void successWithStatusCode() {
Object body = new Object();
Response<Object> response = Response.success(204, body);
assertThat(response.code()).isEqualTo(204);
assertThat(response.message()).isEqualTo("Response.success()");
assertThat(response.headers().size()).isZero();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(body);
assertThat(response.errorBody()).isNull();
}
@Test
public void successWithRawResponse() {
Object body = new Object();
Response<Object> response = Response.success(body, successResponse);
assertThat(response.raw()).isSameAs(successResponse);
assertThat(response.code()).isEqualTo(200);
assertThat(response.message()).isEqualTo("OK");
assertThat(response.headers().size()).isZero();
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body()).isSameAs(body);
assertThat(response.errorBody()).isNull();
}
@Test
public void successWithNullRawResponseThrows() {
try {
Response.success("", (okhttp3.Response) null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("rawResponse == null");
}
}
@Test
public void successWithErrorRawResponseThrows() {
try {
Response.success("", errorResponse);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("rawResponse must be successful response");
}
}
@Test
public void error() {
MediaType plainText = MediaType.get("text/plain; charset=utf-8");
ResponseBody errorBody = ResponseBody.create(plainText, "Broken!");
Response<?> response = Response.error(400, errorBody);
assertThat(response.raw()).isNotNull();
assertThat(response.raw().body().contentType()).isEqualTo(plainText);
assertThat(response.raw().body().contentLength()).isEqualTo(7);
try {
response.raw().body().source();
fail();
} catch (IllegalStateException expected) {
}
assertThat(response.code()).isEqualTo(400);
assertThat(response.message()).isEqualTo("Response.error()");
assertThat(response.headers().size()).isZero();
assertThat(response.isSuccessful()).isFalse();
assertThat(response.body()).isNull();
assertThat(response.errorBody()).isSameAs(errorBody);
}
@Test
public void nullErrorThrows() {
try {
Response.error(400, null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("body == null");
}
}
@Test
public void errorWithSuccessCodeThrows() {
ResponseBody errorBody = ResponseBody.create(null, "Broken!");
try {
Response.error(200, errorBody);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("code < 400: 200");
}
}
@Test
public void errorWithRawResponse() {
ResponseBody errorBody = ResponseBody.create(null, "Broken!");
Response<?> response = Response.error(errorBody, errorResponse);
assertThat(response.raw()).isSameAs(errorResponse);
assertThat(response.code()).isEqualTo(400);
assertThat(response.message()).isEqualTo("Broken!");
assertThat(response.headers().size()).isZero();
assertThat(response.isSuccessful()).isFalse();
assertThat(response.body()).isNull();
assertThat(response.errorBody()).isSameAs(errorBody);
}
@Test
public void nullErrorWithRawResponseThrows() {
try {
Response.error(null, errorResponse);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("body == null");
}
}
@Test
public void errorWithNullRawResponseThrows() {
ResponseBody errorBody = ResponseBody.create(null, "Broken!");
try {
Response.error(errorBody, null);
fail();
} catch (NullPointerException e) {
assertThat(e).hasMessage("rawResponse == null");
}
}
@Test
public void errorWithSuccessRawResponseThrows() {
ResponseBody errorBody = ResponseBody.create(null, "Broken!");
try {
Response.error(errorBody, successResponse);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("rawResponse should not be successful response");
}
}
}
| 3,695 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/OptionalConverterFactoryTest.java | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Optional;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ObjectInstanceConverterFactory;
import retrofit2.http.GET;
public final class OptionalConverterFactoryTest {
interface Service {
@GET("/")
Call<Optional<Object>> optional();
@GET("/")
Call<Object> object();
}
@Rule public final MockWebServer server = new MockWebServer();
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ObjectInstanceConverterFactory())
.build();
service = retrofit.create(Service.class);
}
@Test
public void optional() throws IOException {
server.enqueue(new MockResponse());
Optional<Object> optional = service.optional().execute().body();
assertThat(optional).isNotNull();
assertThat(optional.get()).isSameAs(ObjectInstanceConverterFactory.VALUE);
}
@Test
public void onlyMatchesOptional() throws IOException {
server.enqueue(new MockResponse());
Object body = service.object().execute().body();
assertThat(body).isSameAs(ObjectInstanceConverterFactory.VALUE);
}
}
| 3,696 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/CompletableFutureCallAdapterFactoryTest.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import retrofit2.helpers.ToStringConverterFactory;
public final class CompletableFutureCallAdapterFactoryTest {
private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
@Rule public final MockWebServer server = new MockWebServer();
private final CallAdapter.Factory factory = new CompletableFutureCallAdapterFactory();
private Retrofit retrofit;
@Before
public void setUp() {
retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
}
@Test
public void responseType() {
Type bodyClass = new TypeToken<CompletableFuture<String>>() {}.getType();
assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type bodyWildcard = new TypeToken<CompletableFuture<? extends String>>() {}.getType();
assertThat(factory.get(bodyWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type bodyGeneric = new TypeToken<CompletableFuture<List<String>>>() {}.getType();
assertThat(factory.get(bodyGeneric, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(new TypeToken<List<String>>() {}.getType());
Type responseClass = new TypeToken<CompletableFuture<Response<String>>>() {}.getType();
assertThat(factory.get(responseClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type responseWildcard =
new TypeToken<CompletableFuture<Response<? extends String>>>() {}.getType();
assertThat(factory.get(responseWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type resultClass = new TypeToken<CompletableFuture<Response<String>>>() {}.getType();
assertThat(factory.get(resultClass, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
Type resultWildcard =
new TypeToken<CompletableFuture<Response<? extends String>>>() {}.getType();
assertThat(factory.get(resultWildcard, NO_ANNOTATIONS, retrofit).responseType())
.isEqualTo(String.class);
}
@Test
public void nonListenableFutureReturnsNull() {
CallAdapter<?, ?> adapter = factory.get(String.class, NO_ANNOTATIONS, retrofit);
assertThat(adapter).isNull();
}
@Test
public void rawTypeThrows() {
Type observableType = new TypeToken<CompletableFuture>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage(
"CompletableFuture return type must be parameterized as CompletableFuture<Foo> or CompletableFuture<? extends Foo>");
}
}
@Test
public void rawResponseTypeThrows() {
Type observableType = new TypeToken<CompletableFuture<Response>>() {}.getType();
try {
factory.get(observableType, NO_ANNOTATIONS, retrofit);
fail();
} catch (IllegalStateException e) {
assertThat(e)
.hasMessage("Response must be parameterized as Response<Foo> or Response<? extends Foo>");
}
}
}
| 3,697 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/RequestFactoryTest.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static retrofit2.TestingUtils.buildRequest;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import org.junit.Ignore;
import org.junit.Test;
import retrofit2.helpers.NullObjectConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.HEAD;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.OPTIONS;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.QueryName;
import retrofit2.http.Tag;
import retrofit2.http.Url;
@SuppressWarnings({"UnusedParameters", "unused"}) // Parameters inspected reflectively.
public final class RequestFactoryTest {
private static final MediaType TEXT_PLAIN = MediaType.get("text/plain");
@Test
public void customMethodNoBody() {
class Example {
@HTTP(method = "CUSTOM1", path = "/foo")
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("CUSTOM1");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo");
assertThat(request.body()).isNull();
}
@Test
public void customMethodWithBody() {
class Example {
@HTTP(method = "CUSTOM2", path = "/foo", hasBody = true)
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo("CUSTOM2");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo");
assertBody(request.body(), "hi");
}
@Test
public void onlyOneEncodingIsAllowedMultipartFirst() {
class Example {
@Multipart //
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Only one encoding annotation is allowed.\n for method Example.method");
}
}
@Test
public void onlyOneEncodingIsAllowedFormEncodingFirst() {
class Example {
@FormUrlEncoded //
@Multipart //
@POST("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Only one encoding annotation is allowed.\n for method Example.method");
}
}
@Test
public void invalidPathParam() throws Exception {
class Example {
@GET("/") //
Call<ResponseBody> method(@Path("hey!") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}."
+ " Found: hey! (parameter #1)\n for method Example.method");
}
}
@Test
public void pathParamNotAllowedInQuery() throws Exception {
class Example {
@GET("/foo?bar={bar}") //
Call<ResponseBody> method(@Path("bar") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"URL query string \"bar={bar}\" must not have replace block."
+ " For dynamic query parameters use @Query.\n for method Example.method");
}
}
@Test
public void multipleParameterAnnotationsNotAllowed() throws Exception {
class Example {
@GET("/") //
Call<ResponseBody> method(@Body @Query("nope") String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method");
}
}
@interface NonNull {}
@Test
public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception {
class Example {
@GET("/") //
Call<ResponseBody> method(@Query("maybe") @NonNull Object o) {
return null;
}
}
Request request = buildRequest(Example.class, "yep");
assertThat(request.url().toString()).isEqualTo("http://example.com/?maybe=yep");
}
@Test
public void twoMethodsFail() {
class Example {
@PATCH("/foo") //
@POST("/foo") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isIn(
"Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method",
"Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method");
}
}
@Test
public void lackingMethod() {
class Example {
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method");
}
}
@Test
public void implicitMultipartForbidden() {
class Example {
@POST("/") //
Call<ResponseBody> method(@Part("a") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method");
}
}
@Test
public void implicitMultipartWithPartMapForbidden() {
class Example {
@POST("/") //
Call<ResponseBody> method(@PartMap Map<String, String> params) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method");
}
}
@Test
public void multipartFailsOnNonBodyMethod() {
class Example {
@Multipart //
@GET("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method");
}
}
@Test
public void multipartFailsWithNoParts() {
class Example {
@Multipart //
@POST("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Multipart method must contain at least one @Part.\n for method Example.method");
}
}
@Test
public void implicitFormEncodingByFieldForbidden() {
class Example {
@POST("/") //
Call<ResponseBody> method(@Field("a") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method");
}
}
@Test
public void implicitFormEncodingByFieldMapForbidden() {
class Example {
@POST("/") //
Call<ResponseBody> method(@FieldMap Map<String, String> a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method");
}
}
@Test
public void formEncodingFailsOnNonBodyMethod() {
class Example {
@FormUrlEncoded //
@GET("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method");
}
}
@Test
public void formEncodingFailsWithNoParts() {
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Form-encoded method must contain at least one @Field.\n for method Example.method");
}
}
@Test
public void headersFailWhenEmptyOnMethod() {
class Example {
@GET("/") //
@Headers({}) //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("@Headers annotation is empty.\n for method Example.method");
}
}
@Test
public void headersFailWhenMalformed() {
class Example {
@GET("/") //
@Headers("Malformed") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Headers value must be in the form \"Name: Value\". Found: \"Malformed\"\n for method Example.method");
}
}
@Test
public void pathParamNonPathParamAndTypedBytes() {
class Example {
@PUT("/{a}") //
Call<ResponseBody> method(@Path("a") int a, @Path("b") int b, @Body int c) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"URL \"/{a}\" does not contain \"{b}\". (parameter #2)\n for method Example.method");
}
}
@Test
public void parameterWithoutAnnotation() {
class Example {
@GET("/") //
Call<ResponseBody> method(String a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"No Retrofit annotation found. (parameter #1)\n for method Example.method");
}
}
@Test
public void nonBodyHttpMethodWithSingleEntity() {
class Example {
@GET("/") //
Call<ResponseBody> method(@Body String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Non-body HTTP method cannot contain @Body.\n for method Example.method");
}
}
@Test
public void queryMapMustBeAMap() {
class Example {
@GET("/") //
Call<ResponseBody> method(@QueryMap List<String> a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method");
}
}
@Test
public void queryMapSupportsSubclasses() {
class Foo extends HashMap<String, String> {}
class Example {
@GET("/") //
Call<ResponseBody> method(@QueryMap Foo a) {
return null;
}
}
Foo foo = new Foo();
foo.put("hello", "world");
Request request = buildRequest(Example.class, foo);
assertThat(request.url().toString()).isEqualTo("http://example.com/?hello=world");
}
@Test
public void queryMapRejectsNull() {
class Example {
@GET("/") //
Call<ResponseBody> method(@QueryMap Map<String, String> a) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Query map was null (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void queryMapRejectsNullKeys() {
class Example {
@GET("/") //
Call<ResponseBody> method(@QueryMap Map<String, String> a) {
return null;
}
}
Map<String, String> queryParams = new LinkedHashMap<>();
queryParams.put("ping", "pong");
queryParams.put(null, "kat");
try {
buildRequest(Example.class, queryParams);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Query map contained null key. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void queryMapRejectsNullValues() {
class Example {
@GET("/") //
Call<ResponseBody> method(@QueryMap Map<String, String> a) {
return null;
}
}
Map<String, String> queryParams = new LinkedHashMap<>();
queryParams.put("ping", "pong");
queryParams.put("kit", null);
try {
buildRequest(Example.class, queryParams);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Query map contained null value for key 'kit'. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithHeaderMap() {
class Example {
@GET("/search")
Call<ResponseBody> method(@HeaderMap Map<String, Object> headers) {
return null;
}
}
Map<String, Object> headers = new LinkedHashMap<>();
headers.put("Accept", "text/plain");
headers.put("Accept-Charset", "utf-8");
Request request = buildRequest(Example.class, headers);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.url().toString()).isEqualTo("http://example.com/search");
assertThat(request.body()).isNull();
assertThat(request.headers().size()).isEqualTo(2);
assertThat(request.header("Accept")).isEqualTo("text/plain");
assertThat(request.header("Accept-Charset")).isEqualTo("utf-8");
}
@Test
public void headerMapMustBeAMapOrHeaders() {
class Example {
@GET("/")
Call<ResponseBody> method(@HeaderMap okhttp3.Headers headers, @HeaderMap List<String> headerMap) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@HeaderMap parameter type must be Map or Headers. (parameter #2)\n for method Example.method");
}
}
@Test
public void headerMapSupportsSubclasses() {
class Foo extends HashMap<String, String> {}
class Example {
@GET("/search")
Call<ResponseBody> method(@HeaderMap Foo headers) {
return null;
}
}
Foo headers = new Foo();
headers.put("Accept", "text/plain");
Request request = buildRequest(Example.class, headers);
assertThat(request.url().toString()).isEqualTo("http://example.com/search");
assertThat(request.headers().size()).isEqualTo(1);
assertThat(request.header("Accept")).isEqualTo("text/plain");
}
@Test
public void headerMapRejectsNull() {
class Example {
@GET("/")
Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
return null;
}
}
try {
buildRequest(Example.class, (Map<String, String>) null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Header map was null. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void headerMapRejectsNullKeys() {
class Example {
@GET("/")
Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
return null;
}
}
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Accept", "text/plain");
headers.put(null, "utf-8");
try {
buildRequest(Example.class, headers);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Header map contained null key. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void headerMapRejectsNullValues() {
class Example {
@GET("/")
Call<ResponseBody> method(@HeaderMap Map<String, String> headers) {
return null;
}
}
Map<String, String> headers = new LinkedHashMap<>();
headers.put("Accept", "text/plain");
headers.put("Accept-Charset", null);
try {
buildRequest(Example.class, headers);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Header map contained null value for key 'Accept-Charset'. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithHeaders() {
class Example {
@GET("/search")
Call<ResponseBody> method(@HeaderMap okhttp3.Headers headers) {
throw new AssertionError();
}
}
okhttp3.Headers headers =
new okhttp3.Headers.Builder()
.add("Accept", "text/plain")
.add("Accept", "application/json")
.add("Accept-Charset", "utf-8")
.build();
Request request = buildRequest(Example.class, headers);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.url().toString()).isEqualTo("http://example.com/search");
assertThat(request.body()).isNull();
assertThat(request.headers().size()).isEqualTo(3);
assertThat(request.headers("Accept")).isEqualTo(asList("text/plain", "application/json"));
assertThat(request.header("Accept-Charset")).isEqualTo("utf-8");
}
@Test
public void getWithHeadersAndHeaderMap() {
class Example {
@GET("/search")
Call<ResponseBody> method(
@HeaderMap okhttp3.Headers headers, @HeaderMap Map<String, Object> headerMap) {
throw new AssertionError();
}
}
okhttp3.Headers headers =
new okhttp3.Headers.Builder()
.add("Accept", "text/plain")
.add("Accept-Charset", "utf-8")
.build();
Map<String, String> headerMap = Collections.singletonMap("Accept", "application/json");
Request request = buildRequest(Example.class, headers, headerMap);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.url().toString()).isEqualTo("http://example.com/search");
assertThat(request.body()).isNull();
assertThat(request.headers().size()).isEqualTo(3);
assertThat(request.headers("Accept")).isEqualTo(asList("text/plain", "application/json"));
assertThat(request.header("Accept-Charset")).isEqualTo("utf-8");
}
@Test
public void headersRejectsNull() {
class Example {
@GET("/")
Call<ResponseBody> method(@HeaderMap okhttp3.Headers headers) {
throw new AssertionError();
}
}
try {
buildRequest(Example.class, (okhttp3.Headers) null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Headers parameter must not be null. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithHeaderMapAllowingUnsafeNonAsciiValues() {
class Example {
@GET("/search")
Call<ResponseBody> method(
@HeaderMap(allowUnsafeNonAsciiValues = true) Map<String, Object> headers) {
return null;
}
}
Map<String, Object> headers = new LinkedHashMap<>();
headers.put("Accept", "text/plain");
headers.put("Title", "Kein plötzliches");
Request request = buildRequest(Example.class, headers);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.url().toString()).isEqualTo("http://example.com/search");
assertThat(request.body()).isNull();
assertThat(request.headers().size()).isEqualTo(2);
assertThat(request.header("Accept")).isEqualTo("text/plain");
assertThat(request.header("Title")).isEqualTo("Kein plötzliches");
}
@Test
public void twoBodies() {
class Example {
@PUT("/") //
Call<ResponseBody> method(@Body String o1, @Body String o2) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Multiple @Body method annotations found. (parameter #2)\n for method Example.method");
}
}
@Test
public void bodyInNonBodyRequest() {
class Example {
@Multipart //
@PUT("/") //
Call<ResponseBody> method(@Part("one") String o1, @Body String o2) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method");
}
}
@Test
public void get() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void delete() {
class Example {
@DELETE("/foo/bar/") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("DELETE");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertNull(request.body());
}
@Test
public void headVoid() {
class Example {
@HEAD("/foo/bar/") //
Call<Void> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("HEAD");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Ignore("This test is valid but isn't validated by RequestFactory so it needs moved")
@Test
public void headWithoutVoidThrows() {
class Example {
@HEAD("/foo/bar/") //
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"HEAD method must use Void or Unit as response type.\n for method Example.method");
}
}
@Test
public void post() {
class Example {
@POST("/foo/bar/") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertBody(request.body(), "hi");
}
@Test
public void put() {
class Example {
@PUT("/foo/bar/") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo("PUT");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertBody(request.body(), "hi");
}
@Test
public void patch() {
class Example {
@PATCH("/foo/bar/") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo("PATCH");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertBody(request.body(), "hi");
}
@Test
public void options() {
class Example {
@OPTIONS("/foo/bar/") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("OPTIONS");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithPathParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "po ng");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/");
assertThat(request.body()).isNull();
}
@Test
public void getWithUnusedAndInvalidNamedPathParam() {
class Example {
@GET("/foo/bar/{ping}/{kit,kat}/") //
Call<ResponseBody> method(@Path("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "pong");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/pong/%7Bkit,kat%7D/");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedPathParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "po%20ng");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/po%20ng/");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedPathSegments() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "baz/pong/more");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/more/");
assertThat(request.body()).isNull();
}
@Test
public void getWithUnencodedPathSegmentsPreventsRequestSplitting() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = false) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "baz/\r\nheader: blue");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/baz%2F%0D%0Aheader:%20blue/");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedPathStillPreventsRequestSplitting() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "baz/\r\npong");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/baz/pong/");
assertThat(request.body()).isNull();
}
@Test
public void pathParametersAndPathTraversal() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping") String ping) {
return null;
}
}
assertMalformedRequest(Example.class, ".");
assertMalformedRequest(Example.class, "..");
assertThat(buildRequest(Example.class, "./a").url().encodedPath()).isEqualTo("/foo/bar/.%2Fa/");
assertThat(buildRequest(Example.class, "a/.").url().encodedPath()).isEqualTo("/foo/bar/a%2F./");
assertThat(buildRequest(Example.class, "a/..").url().encodedPath())
.isEqualTo("/foo/bar/a%2F../");
assertThat(buildRequest(Example.class, "../a").url().encodedPath())
.isEqualTo("/foo/bar/..%2Fa/");
assertThat(buildRequest(Example.class, "..\\..").url().encodedPath())
.isEqualTo("/foo/bar/..%5C../");
assertThat(buildRequest(Example.class, "%2E").url().encodedPath()).isEqualTo("/foo/bar/%252E/");
assertThat(buildRequest(Example.class, "%2E%2E").url().encodedPath())
.isEqualTo("/foo/bar/%252E%252E/");
}
@Test
public void encodedPathParametersAndPathTraversal() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
assertMalformedRequest(Example.class, ".");
assertMalformedRequest(Example.class, "%2E");
assertMalformedRequest(Example.class, "%2e");
assertMalformedRequest(Example.class, "..");
assertMalformedRequest(Example.class, "%2E.");
assertMalformedRequest(Example.class, "%2e.");
assertMalformedRequest(Example.class, ".%2E");
assertMalformedRequest(Example.class, ".%2e");
assertMalformedRequest(Example.class, "%2E%2e");
assertMalformedRequest(Example.class, "%2e%2E");
assertMalformedRequest(Example.class, "./a");
assertMalformedRequest(Example.class, "a/.");
assertMalformedRequest(Example.class, "../a");
assertMalformedRequest(Example.class, "a/..");
assertMalformedRequest(Example.class, "a/../b");
assertMalformedRequest(Example.class, "a/%2e%2E/b");
assertThat(buildRequest(Example.class, "...").url().encodedPath()).isEqualTo("/foo/bar/.../");
assertThat(buildRequest(Example.class, "a..b").url().encodedPath()).isEqualTo("/foo/bar/a..b/");
assertThat(buildRequest(Example.class, "a..").url().encodedPath()).isEqualTo("/foo/bar/a../");
assertThat(buildRequest(Example.class, "a..b").url().encodedPath()).isEqualTo("/foo/bar/a..b/");
assertThat(buildRequest(Example.class, "..b").url().encodedPath()).isEqualTo("/foo/bar/..b/");
assertThat(buildRequest(Example.class, "..\\..").url().encodedPath())
.isEqualTo("/foo/bar/..%5C../");
}
@Test
public void dotDotsOkayWhenNotFullPathSegment() {
class Example {
@GET("/foo{ping}bar/") //
Call<ResponseBody> method(@Path(value = "ping", encoded = true) String ping) {
return null;
}
}
assertMalformedRequest(Example.class, "/./");
assertMalformedRequest(Example.class, "/../");
assertThat(buildRequest(Example.class, ".").url().encodedPath()).isEqualTo("/foo.bar/");
assertThat(buildRequest(Example.class, "..").url().encodedPath()).isEqualTo("/foo..bar/");
}
@Test
public void pathParamRequired() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isEqualTo(
"Path parameter \"ping\" value must not be null. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryParam() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "pong");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?ping=pong");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedQueryParam() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query(value = "pi%20ng", encoded = true) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "p%20o%20n%20g");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g");
assertThat(request.body()).isNull();
}
@Test
public void queryParamOptionalOmitsQuery() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, new Object[] {null});
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
}
@Test
public void queryParamOptional() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(
@Query("foo") String foo, @Query("ping") String ping, @Query("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "bar", null, "kat");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?foo=bar&kit=kat");
}
@Test
public void getWithQueryUrlAndParam() {
class Example {
@GET("/foo/bar/?hi=mom") //
Call<ResponseBody> method(@Query("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "pong");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom&ping=pong");
assertThat(request.body()).isNull();
}
@Test
public void getWithQuery() {
class Example {
@GET("/foo/bar/?hi=mom") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hi=mom");
assertThat(request.body()).isNull();
}
@Test
public void getWithPathAndQueryParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(
@Path("ping") String ping, @Query("kit") String kit, @Query("riff") String riff) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", "kat", "raff");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryThenPathThrows() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Query("kit") String kit, @Path("ping") String ping) {
return null;
}
}
try {
buildRequest(Example.class, "kat", "pong");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Path parameter must not come after a @Query. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryNameThenPathThrows() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@QueryName String kit, @Path("ping") String ping) {
throw new AssertionError();
}
}
try {
buildRequest(Example.class, "kat", "pong");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Path parameter must not come after a @QueryName. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryMapThenPathThrows() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Path("ping") String ping) {
throw new AssertionError();
}
}
try {
buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "pong");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Path parameter must not come after a @QueryMap. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithPathAndQueryQuestionMarkParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong?", "kat?");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/pong%3F/?kit=kat%3F");
assertThat(request.body()).isNull();
}
@Test
public void getWithPathAndQueryAmpersandParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong&", "kat&");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong&/?kit=kat%26");
assertThat(request.body()).isNull();
}
@Test
public void getWithPathAndQueryHashParam() {
class Example {
@GET("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping, @Query("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong#", "kat#");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/pong%23/?kit=kat%23");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryParamList() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("key") List<Object> keys) {
return null;
}
}
List<Object> values = Arrays.asList(1, 2, null, "three", "1");
Request request = buildRequest(Example.class, values);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryParamArray() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("key") Object[] keys) {
return null;
}
}
Object[] values = {1, 2, null, "three", "1"};
Request request = buildRequest(Example.class, new Object[] {values});
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=three&key=1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryParamPrimitiveArray() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Query("key") int[] keys) {
return null;
}
}
int[] values = {1, 2, 3, 1};
Request request = buildRequest(Example.class, new Object[] {values});
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?key=1&key=2&key=3&key=1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryNameParam() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "pong");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?pong");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedQueryNameParam() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName(encoded = true) String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "p%20o%20n%20g");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?p%20o%20n%20g");
assertThat(request.body()).isNull();
}
@Test
public void queryNameParamOptionalOmitsQuery() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName String ping) {
return null;
}
}
Request request = buildRequest(Example.class, new Object[] {null});
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
}
@Test
public void getWithQueryNameParamList() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName List<Object> keys) {
return null;
}
}
List<Object> values = Arrays.asList(1, 2, null, "three", "1");
Request request = buildRequest(Example.class, values);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryNameParamArray() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName Object[] keys) {
return null;
}
}
Object[] values = {1, 2, null, "three", "1"};
Request request = buildRequest(Example.class, new Object[] {values});
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&three&1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryNameParamPrimitiveArray() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryName int[] keys) {
return null;
}
}
int[] values = {1, 2, 3, 1};
Request request = buildRequest(Example.class, new Object[] {values});
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?1&2&3&1");
assertThat(request.body()).isNull();
}
@Test
public void getWithQueryParamMap() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryMap Map<String, Object> query) {
return null;
}
}
Map<String, Object> params = new LinkedHashMap<>();
params.put("kit", "kat");
params.put("ping", "pong");
Request request = buildRequest(Example.class, params);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?kit=kat&ping=pong");
assertThat(request.body()).isNull();
}
@Test
public void getWithEncodedQueryParamMap() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@QueryMap(encoded = true) Map<String, Object> query) {
return null;
}
}
Map<String, Object> params = new LinkedHashMap<>();
params.put("kit", "k%20t");
params.put("pi%20ng", "p%20g");
Request request = buildRequest(Example.class, params);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString())
.isEqualTo("http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g");
assertThat(request.body()).isNull();
}
@Test
public void getAbsoluteUrl() {
class Example {
@GET("http://example2.com/foo/bar/")
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example2.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithStringUrl() {
class Example {
@GET
Call<ResponseBody> method(@Url String url) {
return null;
}
}
Request request = buildRequest(Example.class, "foo/bar/");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithJavaUriUrl() {
class Example {
@GET
Call<ResponseBody> method(@Url URI url) {
return null;
}
}
Request request = buildRequest(Example.class, URI.create("foo/bar/"));
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithStringUrlAbsolute() {
class Example {
@GET
Call<ResponseBody> method(@Url String url) {
return null;
}
}
Request request = buildRequest(Example.class, "https://example2.com/foo/bar/");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithJavaUriUrlAbsolute() {
class Example {
@GET
Call<ResponseBody> method(@Url URI url) {
return null;
}
}
Request request = buildRequest(Example.class, URI.create("https://example2.com/foo/bar/"));
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithUrlAbsoluteSameHost() {
class Example {
@GET
Call<ResponseBody> method(@Url String url) {
return null;
}
}
Request request = buildRequest(Example.class, "http://example.com/foo/bar/");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithHttpUrl() {
class Example {
@GET
Call<ResponseBody> method(@Url HttpUrl url) {
return null;
}
}
Request request = buildRequest(Example.class, HttpUrl.get("http://example.com/foo/bar/"));
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url()).isEqualTo(HttpUrl.get("http://example.com/foo/bar/"));
assertThat(request.body()).isNull();
}
@Test
public void getWithNullUrl() {
class Example {
@GET
Call<ResponseBody> method(@Url HttpUrl url) {
return null;
}
}
try {
buildRequest(Example.class, (HttpUrl) null);
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessage("@Url parameter is null. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void getWithNonStringUrlThrows() {
class Example {
@GET
Call<ResponseBody> method(@Url Object url) {
return null;
}
}
try {
buildRequest(Example.class, "foo/bar");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type."
+ " (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getUrlAndUrlParamThrows() {
class Example {
@GET("foo/bar")
Call<ResponseBody> method(@Url Object url) {
return null;
}
}
try {
buildRequest(Example.class, "foo/bar");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Url cannot be used with @GET URL (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithoutUrlThrows() {
class Example {
@GET
Call<ResponseBody> method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Missing either @GET URL or @Url parameter.\n" + " for method Example.method");
}
}
@Test
public void getWithUrlThenPathThrows() {
class Example {
@GET
Call<ResponseBody> method(@Url String url, @Path("hey") String hey) {
return null;
}
}
try {
buildRequest(Example.class, "foo/bar");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Path parameters may not be used with @Url. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithPathThenUrlThrows() {
class Example {
@GET
Call<ResponseBody> method(@Path("hey") String hey, @Url Object url) {
return null;
}
}
try {
buildRequest(Example.class, "foo/bar");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Path can only be used with relative url on @GET (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryThenUrlThrows() {
class Example {
@GET("foo/bar")
Call<ResponseBody> method(@Query("hey") String hey, @Url Object url) {
return null;
}
}
try {
buildRequest(Example.class, "hey", "foo/bar/");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Url parameter must not come after a @Query. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryNameThenUrlThrows() {
class Example {
@GET
Call<ResponseBody> method(@QueryName String name, @Url String url) {
throw new AssertionError();
}
}
try {
buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Url parameter must not come after a @QueryName. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithQueryMapThenUrlThrows() {
class Example {
@GET
Call<ResponseBody> method(@QueryMap Map<String, String> queries, @Url String url) {
throw new AssertionError();
}
}
try {
buildRequest(Example.class, Collections.singletonMap("kit", "kat"), "foo/bar/");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"A @Url parameter must not come after a @QueryMap. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void getWithUrlThenQuery() {
class Example {
@GET
Call<ResponseBody> method(@Url String url, @Query("hey") String hey) {
return null;
}
}
Request request = buildRequest(Example.class, "foo/bar/", "hey!");
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/?hey=hey%21");
}
@Test
public void postWithUrl() {
class Example {
@POST
Call<ResponseBody> method(@Url String url, @Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, "http://example.com/foo/bar", body);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar");
assertBody(request.body(), "hi");
}
@Test
public void normalPostWithPathParam() {
class Example {
@POST("/foo/bar/{ping}/") //
Call<ResponseBody> method(@Path("ping") String ping, @Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!");
Request request = buildRequest(Example.class, "pong", body);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/");
assertBody(request.body(), "Hi!");
}
@Test
public void emptyBody() {
class Example {
@POST("/foo/bar/") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertBody(request.body(), "");
}
@Test
public void customMethodEmptyBody() {
class Example {
@HTTP(method = "CUSTOM", path = "/foo/bar/", hasBody = true) //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("CUSTOM");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertBody(request.body(), "");
}
@Test
public void bodyRequired() {
class Example {
@POST("/foo/bar/") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isEqualTo(
"Body parameter value must not be null. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void bodyWithPathParams() {
class Example {
@POST("/foo/bar/{ping}/{kit}/") //
Call<ResponseBody> method(
@Path("ping") String ping, @Body RequestBody body, @Path("kit") String kit) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "Hi!");
Request request = buildRequest(Example.class, "pong", body, "kat");
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/pong/kat/");
assertBody(request.body(), "Hi!");
}
@Test
public void simpleMultipart() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") String ping, @Part("kit") RequestBody kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", RequestBody.create(TEXT_PLAIN, "kat"));
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
assertThat(body.contentType().toString()).startsWith("multipart/form-data; boundary=");
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartArray() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") String[] ping) {
return null;
}
}
Request request = buildRequest(Example.class, new Object[] {new String[] {"pong1", "pong2"}});
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong1\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"")
.contains("\r\npong2\r\n--");
}
@Test
public void multipartRequiresName() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part RequestBody part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartIterableRequiresName() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part List<RequestBody> part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartArrayRequiresName() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part RequestBody[] part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartOkHttpPartForbidsName() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("name") MultipartBody.Part part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartOkHttpPart() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part MultipartBody.Part part) {
return null;
}
}
MultipartBody.Part part = MultipartBody.Part.createFormData("kit", "kat");
Request request = buildRequest(Example.class, part);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"\r\n")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartOkHttpIterablePart() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part List<MultipartBody.Part> part) {
return null;
}
}
MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar");
MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat");
Request request = buildRequest(Example.class, asList(part1, part2));
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"foo\"\r\n")
.contains("\r\nbar\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"\r\n")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartOkHttpArrayPart() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part MultipartBody.Part[] part) {
return null;
}
}
MultipartBody.Part part1 = MultipartBody.Part.createFormData("foo", "bar");
MultipartBody.Part part2 = MultipartBody.Part.createFormData("kit", "kat");
Request request =
buildRequest(Example.class, new Object[] {new MultipartBody.Part[] {part1, part2}});
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"foo\"\r\n")
.contains("\r\nbar\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"\r\n")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartOkHttpPartWithFilename() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part MultipartBody.Part part) {
return null;
}
}
MultipartBody.Part part =
MultipartBody.Part.createFormData("kit", "kit.txt", RequestBody.create(null, "kat"));
Request request = buildRequest(Example.class, part);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"; filename=\"kit.txt\"\r\n")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartIterable() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") List<String> ping) {
return null;
}
}
Request request = buildRequest(Example.class, asList("pong1", "pong2"));
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong1\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"")
.contains("\r\npong2\r\n--");
}
@Test
public void multipartIterableOkHttpPart() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") List<MultipartBody.Part> part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartArrayOkHttpPart() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") MultipartBody.Part[] part) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartWithEncoding() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(
@Part(value = "ping", encoding = "8-bit") String ping,
@Part(value = "kit", encoding = "7-bit") RequestBody kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", RequestBody.create(TEXT_PLAIN, "kat"));
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\npong\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("Content-Transfer-Encoding: 7-bit")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartPartMap() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) {
return null;
}
}
Map<String, RequestBody> params = new LinkedHashMap<>();
params.put("ping", RequestBody.create(null, "pong"));
params.put("kit", RequestBody.create(null, "kat"));
Request request = buildRequest(Example.class, params);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("\r\npong\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartPartMapWithEncoding() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap(encoding = "8-bit") Map<String, RequestBody> parts) {
return null;
}
}
Map<String, RequestBody> params = new LinkedHashMap<>();
params.put("ping", RequestBody.create(null, "pong"));
params.put("kit", RequestBody.create(null, "kat"));
Request request = buildRequest(Example.class, params);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"\r\n")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\npong\r\n--");
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"kit\"")
.contains("Content-Transfer-Encoding: 8-bit")
.contains("\r\nkat\r\n--");
}
@Test
public void multipartPartMapRejectsNonStringKeys() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<Object, RequestBody> parts) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@PartMap keys must be of type String: class java.lang.Object (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartPartMapRejectsOkHttpPartValues() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<String, MultipartBody.Part> parts) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@PartMap values cannot be MultipartBody.Part. Use @Part List<Part> or a different value type instead. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartPartMapRejectsNull() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Part map was null. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void multipartPartMapRejectsNullKeys() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) {
return null;
}
}
Map<String, RequestBody> params = new LinkedHashMap<>();
params.put("ping", RequestBody.create(null, "pong"));
params.put(null, RequestBody.create(null, "kat"));
try {
buildRequest(Example.class, params);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Part map contained null key. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void multipartPartMapRejectsNullValues() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Map<String, RequestBody> parts) {
return null;
}
}
Map<String, RequestBody> params = new LinkedHashMap<>();
params.put("ping", RequestBody.create(null, "pong"));
params.put("kit", null);
try {
buildRequest(Example.class, params);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Part map contained null value for key 'kit'. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void multipartPartMapMustBeMap() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap List<Object> parts) {
return null;
}
}
try {
buildRequest(Example.class, emptyList());
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@PartMap parameter type must be Map. (parameter #1)\n for method Example.method");
}
}
@Test
public void multipartPartMapSupportsSubclasses() throws IOException {
class Foo extends HashMap<String, String> {}
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@PartMap Foo parts) {
return null;
}
}
Foo foo = new Foo();
foo.put("hello", "world");
Request request = buildRequest(Example.class, foo);
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
assertThat(buffer.readUtf8()).contains("name=\"hello\"").contains("\r\n\r\nworld\r\n--");
}
@Test
public void multipartNullRemovesPart() throws IOException {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") String ping, @Part("fizz") String fizz) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", null);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isZero();
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString)
.contains("Content-Disposition: form-data;")
.contains("name=\"ping\"")
.contains("\r\npong\r\n--");
}
@Test
public void multipartPartOptional() {
class Example {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") RequestBody ping) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part.");
}
}
@Test
public void simpleFormEncoded() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "bar", "pong");
RequestBody body = request.body();
assertBody(body, "foo=bar&ping=pong");
assertThat(body.contentType().toString()).isEqualTo("application/x-www-form-urlencoded");
}
@Test
public void formEncodedWithEncodedNameFieldParam() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@Field(value = "na%20me", encoded = true) String foo) {
return null;
}
}
Request request = buildRequest(Example.class, "ba%20r");
assertBody(request.body(), "na%20me=ba%20r");
}
@Test
public void formEncodedFieldOptional() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(
@Field("foo") String foo, @Field("ping") String ping, @Field("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "bar", null, "kat");
assertBody(request.body(), "foo=bar&kit=kat");
}
@Test
public void formEncodedFieldList() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@Field("foo") List<Object> fields, @Field("kit") String kit) {
return null;
}
}
List<Object> values = Arrays.asList("foo", "bar", null, 3);
Request request = buildRequest(Example.class, values, "kat");
assertBody(request.body(), "foo=foo&foo=bar&foo=3&kit=kat");
}
@Test
public void formEncodedFieldArray() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@Field("foo") Object[] fields, @Field("kit") String kit) {
return null;
}
}
Object[] values = {1, 2, null, "three"};
Request request = buildRequest(Example.class, values, "kat");
assertBody(request.body(), "foo=1&foo=2&foo=three&kit=kat");
}
@Test
public void formEncodedFieldPrimitiveArray() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@Field("foo") int[] fields, @Field("kit") String kit) {
return null;
}
}
int[] values = {1, 2, 3};
Request request = buildRequest(Example.class, values, "kat");
assertBody(request.body(), "foo=1&foo=2&foo=3&kit=kat");
}
@Test
public void formEncodedWithEncodedNameFieldParamMap() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@FieldMap(encoded = true) Map<String, Object> fieldMap) {
return null;
}
}
Map<String, Object> fieldMap = new LinkedHashMap<>();
fieldMap.put("k%20it", "k%20at");
fieldMap.put("pin%20g", "po%20ng");
Request request = buildRequest(Example.class, fieldMap);
assertBody(request.body(), "k%20it=k%20at&pin%20g=po%20ng");
}
@Test
public void formEncodedFieldMap() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
Call<ResponseBody> method(@FieldMap Map<String, Object> fieldMap) {
return null;
}
}
Map<String, Object> fieldMap = new LinkedHashMap<>();
fieldMap.put("kit", "kat");
fieldMap.put("ping", "pong");
Request request = buildRequest(Example.class, fieldMap);
assertBody(request.body(), "kit=kat&ping=pong");
}
@Test
public void fieldMapRejectsNull() {
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method(@FieldMap Map<String, Object> a) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Field map was null. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void fieldMapRejectsNullKeys() {
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method(@FieldMap Map<String, Object> a) {
return null;
}
}
Map<String, Object> fieldMap = new LinkedHashMap<>();
fieldMap.put("kit", "kat");
fieldMap.put(null, "pong");
try {
buildRequest(Example.class, fieldMap);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Field map contained null key. (parameter #1)\n" + " for method Example.method");
}
}
@Test
public void fieldMapRejectsNullValues() {
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method(@FieldMap Map<String, Object> a) {
return null;
}
}
Map<String, Object> fieldMap = new LinkedHashMap<>();
fieldMap.put("kit", "kat");
fieldMap.put("foo", null);
try {
buildRequest(Example.class, fieldMap);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"Field map contained null value for key 'foo'. (parameter #1)\n"
+ " for method Example.method");
}
}
@Test
public void fieldMapMustBeAMap() {
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method(@FieldMap List<String> a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method");
}
}
@Test
public void fieldMapSupportsSubclasses() throws IOException {
class Foo extends HashMap<String, String> {}
class Example {
@FormUrlEncoded //
@POST("/") //
Call<ResponseBody> method(@FieldMap Foo a) {
return null;
}
}
Foo foo = new Foo();
foo.put("hello", "world");
Request request = buildRequest(Example.class, foo);
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
assertThat(buffer.readUtf8()).isEqualTo("hello=world");
}
@Test
public void simpleHeaders() {
class Example {
@GET("/foo/bar/")
@Headers({"ping: pong", "kit: kat"})
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.get("ping")).isEqualTo("pong");
assertThat(headers.get("kit")).isEqualTo("kat");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void simpleHeadersAllowingUnsafeNonAsciiValues() {
class Example {
@GET("/foo/bar/")
@Headers(
value = {"ping: pong", "title: Kein plötzliches"},
allowUnsafeNonAsciiValues = true)
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.get("ping")).isEqualTo("pong");
assertThat(headers.get("title")).isEqualTo("Kein plötzliches");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headersDoNotOverwriteEachOther() {
class Example {
@GET("/foo/bar/")
@Headers({
"ping: pong",
"kit: kat",
"kit: -kat",
})
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(3);
assertThat(headers.get("ping")).isEqualTo("pong");
assertThat(headers.values("kit")).containsOnly("kat", "-kat");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParamToString() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Header("kit") BigInteger kit) {
return null;
}
}
Request request = buildRequest(Example.class, new BigInteger("1234"));
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(1);
assertThat(headers.get("kit")).isEqualTo("1234");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParam() {
class Example {
@GET("/foo/bar/") //
@Headers("ping: pong") //
Call<ResponseBody> method(@Header("kit") String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "kat");
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.get("ping")).isEqualTo("pong");
assertThat(headers.get("kit")).isEqualTo("kat");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParamAllowingUnsafeNonAsciiValues() {
class Example {
@GET("/foo/bar/") //
@Headers("ping: pong") //
Call<ResponseBody> method(
@Header(value = "title", allowUnsafeNonAsciiValues = true) String kit) {
return null;
}
}
Request request = buildRequest(Example.class, "Kein plötzliches");
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.get("ping")).isEqualTo("pong");
assertThat(headers.get("title")).isEqualTo("Kein plötzliches");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParamList() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Header("foo") List<String> kit) {
return null;
}
}
Request request = buildRequest(Example.class, asList("bar", null, "baz"));
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.values("foo")).containsExactly("bar", "baz");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void headerParamArray() {
class Example {
@GET("/foo/bar/") //
Call<ResponseBody> method(@Header("foo") String[] kit) {
return null;
}
}
Request request = buildRequest(Example.class, (Object) new String[] {"bar", null, "baz"});
assertThat(request.method()).isEqualTo("GET");
okhttp3.Headers headers = request.headers();
assertThat(headers.size()).isEqualTo(2);
assertThat(headers.values("foo")).containsExactly("bar", "baz");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void contentTypeAnnotationHeaderOverrides() {
class Example {
@POST("/") //
@Headers("Content-Type: text/not-plain") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain");
}
@Test
public void contentTypeAnnotationHeaderOverridesFormEncoding() {
class Example {
@FormUrlEncoded //
@POST("/foo") //
@Headers("Content-Type: text/not-plain") //
Call<ResponseBody> method(@Field("foo") String foo, @Field("ping") String ping) {
return null;
}
}
Request request = buildRequest(Example.class, "bar", "pong");
assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain");
}
@Test
public void contentTypeAnnotationHeaderOverridesMultipart() {
class Example {
@Multipart //
@POST("/foo/bar/") //
@Headers("Content-Type: text/not-plain") //
Call<ResponseBody> method(@Part("ping") String ping, @Part("kit") RequestBody kit) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", RequestBody.create(TEXT_PLAIN, "kat"));
RequestBody body = request.body();
assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain");
}
@Test
public void malformedContentTypeHeaderThrows() {
class Example {
@POST("/") //
@Headers("Content-Type: hello, world!") //
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
try {
buildRequest(Example.class, body);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Malformed content type: hello, world!\n" + " for method Example.method");
assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause.
}
}
@Test
public void contentTypeAnnotationHeaderAddsHeaderWithNoBodyGet() {
class Example {
@GET("/") //
@Headers("Content-Type: text/not-plain") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.headers().get("Content-Type")).isEqualTo("text/not-plain");
}
@Test
public void contentTypeAnnotationHeaderAddsHeaderWithNoBodyDelete() {
class Example {
@DELETE("/") //
@Headers("Content-Type: text/not-plain") //
Call<ResponseBody> method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.headers().get("Content-Type")).isEqualTo("text/not-plain");
}
@Test
public void contentTypeParameterHeaderOverrides() {
class Example {
@POST("/") //
Call<ResponseBody> method(
@Header("Content-Type") String contentType, @Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "Plain");
Request request = buildRequest(Example.class, "text/not-plain", body);
assertThat(request.body().contentType().toString()).isEqualTo("text/not-plain");
}
@Test
public void malformedContentTypeParameterThrows() {
class Example {
@POST("/") //
Call<ResponseBody> method(
@Header("Content-Type") String contentType, @Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
try {
buildRequest(Example.class, "hello, world!", body);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Malformed content type: hello, world!");
assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause.
}
}
@Test
public void malformedAnnotationRelativeUrlThrows() {
class Example {
@GET("ftp://example.org")
Call<ResponseBody> get() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Malformed URL. Base: http://example.com/, Relative: ftp://example.org");
}
}
@Test
public void malformedParameterRelativeUrlThrows() {
class Example {
@GET
Call<ResponseBody> get(@Url String relativeUrl) {
return null;
}
}
try {
buildRequest(Example.class, "ftp://example.org");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage("Malformed URL. Base: http://example.com/, Relative: ftp://example.org");
}
}
@Test
public void multipartPartsShouldBeInOrder() throws IOException {
class Example {
@Multipart
@POST("/foo")
Call<ResponseBody> get(
@Part("first") String data,
@Part("second") String dataTwo,
@Part("third") String dataThree) {
return null;
}
}
Request request = buildRequest(Example.class, "firstParam", "secondParam", "thirdParam");
MultipartBody body = (MultipartBody) request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String readBody = buffer.readUtf8();
assertThat(readBody.indexOf("firstParam")).isLessThan(readBody.indexOf("secondParam"));
assertThat(readBody.indexOf("secondParam")).isLessThan(readBody.indexOf("thirdParam"));
}
@Test
public void queryParamsSkippedIfConvertedToNull() throws Exception {
class Example {
@GET("/query")
Call<ResponseBody> queryPath(@Query("a") Object a) {
return null;
}
}
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addConverterFactory(new NullObjectConverterFactory());
Request request = buildRequest(Example.class, retrofitBuilder, "Ignored");
assertThat(request.url().toString()).doesNotContain("Ignored");
}
@Test
public void queryParamMapsConvertedToNullShouldError() throws Exception {
class Example {
@GET("/query")
Call<ResponseBody> queryPath(@QueryMap Map<String, String> a) {
return null;
}
}
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addConverterFactory(new NullObjectConverterFactory());
Map<String, String> queryMap = Collections.singletonMap("kit", "kat");
try {
buildRequest(Example.class, retrofitBuilder, queryMap);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageContaining(
"Query map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.");
}
}
@Test
public void fieldParamsSkippedIfConvertedToNull() throws Exception {
class Example {
@FormUrlEncoded
@POST("/query")
Call<ResponseBody> queryPath(@Field("a") Object a) {
return null;
}
}
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addConverterFactory(new NullObjectConverterFactory());
Request request = buildRequest(Example.class, retrofitBuilder, "Ignored");
assertThat(request.url().toString()).doesNotContain("Ignored");
}
@Test
public void fieldParamMapsConvertedToNullShouldError() throws Exception {
class Example {
@FormUrlEncoded
@POST("/query")
Call<ResponseBody> queryPath(@FieldMap Map<String, String> a) {
return null;
}
}
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addConverterFactory(new NullObjectConverterFactory());
Map<String, String> queryMap = Collections.singletonMap("kit", "kat");
try {
buildRequest(Example.class, retrofitBuilder, queryMap);
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageContaining(
"Field map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.");
}
}
@Test
public void tag() {
class Example {
@GET("/")
Call<ResponseBody> method(@Tag String tag) {
return null;
}
}
Request request = buildRequest(Example.class, "tagValue");
assertThat(request.tag(String.class)).isEqualTo("tagValue");
}
@Test
public void tagGeneric() {
class Example {
@GET("/")
Call<ResponseBody> method(@Tag List<String> tag) {
return null;
}
}
List<String> strings = asList("tag", "value");
Request request = buildRequest(Example.class, strings);
assertThat(request.tag(List.class)).isSameAs(strings);
}
@Test
public void tagDuplicateFails() {
class Example {
@GET("/")
Call<ResponseBody> method(@Tag String one, @Tag String two) {
return null;
}
}
try {
buildRequest(Example.class, "one", "two");
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Tag type java.lang.String is duplicate of parameter #1 and would always overwrite its value. (parameter #2)\n"
+ " for method Example.method");
}
}
@Test
public void tagGenericDuplicateFails() {
class Example {
@GET("/")
Call<ResponseBody> method(@Tag List<String> one, @Tag List<Long> two) {
return null;
}
}
try {
buildRequest(Example.class, emptyList(), emptyList());
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessage(
"@Tag type java.util.List is duplicate of parameter #1 and would always overwrite its value. (parameter #2)\n"
+ " for method Example.method");
}
}
private static void assertBody(RequestBody body, String expected) {
assertThat(body).isNotNull();
Buffer buffer = new Buffer();
try {
body.writeTo(buffer);
assertThat(buffer.readUtf8()).isEqualTo(expected);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static void assertMalformedRequest(Class<?> cls, Object... args) {
try {
Request request = buildRequest(cls, args);
fail("expected a malformed request but was " + request);
} catch (IllegalArgumentException expected) {
// Ignored
}
}
}
| 3,698 |
0 | Create_ds/retrofit/retrofit/src/test/java | Create_ds/retrofit/retrofit/src/test/java/retrofit2/InvocationTest.java | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.junit.Test;
import retrofit2.http.Body;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
public final class InvocationTest {
interface Example {
@POST("/{p1}") //
Call<ResponseBody> postMethod(
@Path("p1") String p1, @Query("p2") String p2, @Body RequestBody body);
}
@Test
public void invocationObjectOnCallAndRequestTag() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://example.com/")
.callFactory(new OkHttpClient())
.build();
Example example = retrofit.create(Example.class);
RequestBody requestBody = RequestBody.create(MediaType.get("text/plain"), "three");
Call<ResponseBody> call = example.postMethod("one", "two", requestBody);
Invocation invocation = call.request().tag(Invocation.class);
Method method = invocation.method();
assertThat(method.getName()).isEqualTo("postMethod");
assertThat(method.getDeclaringClass()).isEqualTo(Example.class);
assertThat(invocation.arguments()).isEqualTo(Arrays.asList("one", "two", requestBody));
}
@Test
public void nullMethod() {
try {
Invocation.of(null, Arrays.asList("one", "two"));
fail();
} catch (NullPointerException expected) {
assertThat(expected).hasMessage("method == null");
}
}
@Test
public void nullArguments() {
try {
Invocation.of(Example.class.getDeclaredMethods()[0], null);
fail();
} catch (NullPointerException expected) {
assertThat(expected).hasMessage("arguments == null");
}
}
@Test
public void argumentsAreImmutable() {
List<String> mutableList = new ArrayList<>(Arrays.asList("one", "two"));
Invocation invocation = Invocation.of(Example.class.getDeclaredMethods()[0], mutableList);
mutableList.add("three");
assertThat(invocation.arguments()).isEqualTo(Arrays.asList("one", "two"));
try {
invocation.arguments().clear();
fail();
} catch (UnsupportedOperationException expected) {
}
}
}
| 3,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.