feign.gson.GsonEncoder Java Examples

The following examples show how to use feign.gson.GsonEncoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarathonClient.java    From marathon-client with Apache License 2.0 7 votes vote down vote up
/**
 * The generalized version of the method that allows more in-depth customizations via
 * {@link RequestInterceptor}s.
 *
 * @param endpoint
 * 		URL of Marathon
 * @param interceptors optional request interceptors
 * @return Marathon client
 */
public static Marathon getInstance(String endpoint, RequestInterceptor... interceptors) {

	Builder b = Feign.builder()
			.encoder(new GsonEncoder(ModelUtils.GSON))
			.decoder(new GsonDecoder(ModelUtils.GSON))
			.errorDecoder(new MarathonErrorDecoder());
	if (interceptors != null)
		b.requestInterceptors(asList(interceptors));
	String debugOutput = System.getenv(DEBUG_JSON_OUTPUT);
	if ("System.out".equals(debugOutput)) {
		System.setProperty("org.slf4j.simpleLogger.logFile", "System.out");
		System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug");
		b.logger(new Slf4jLogger()).logLevel(Logger.Level.FULL);
	} else if (debugOutput != null) {
		b.logger(new Logger.JavaLogger().appendToFile(debugOutput)).logLevel(Logger.Level.FULL);
	}
	b.requestInterceptor(new MarathonHeadersInterceptor());
	return b.target(Marathon.class, endpoint);
}
 
Example #2
Source File: DesignateProvider.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel) {
  RecordAdapter recordAdapter = new RecordAdapter();
  return Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .encoder(new GsonEncoder(Collections.<TypeAdapter<?>>singleton(recordAdapter)))
      .decoder(new GsonDecoder(Arrays.asList(
                   new KeystoneV2AccessAdapter(),
                   recordAdapter,
                   new DomainListAdapter(),
                   new RecordListAdapter()))
      )
      .build();
}
 
Example #3
Source File: HttpZallyService.java    From intellij-swagger with MIT License 6 votes vote down vote up
private static ZallyApi connect() {
  final String zallyUrl = ServiceManager.getService(ZallySettings.class).getZallyUrl();

  if (zallyUrl == null || zallyUrl.isEmpty()) {
    throw new RuntimeException("Zally URL is missing");
  }

  final Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  final Decoder decoder = new GsonDecoder(gson);

  return Feign.builder()
      .encoder(new GsonEncoder())
      .decoder(decoder)
      .errorDecoder(new LintingResponseErrorDecoder())
      .logger(new Logger.ErrorLogger())
      .logLevel(Logger.Level.BASIC)
      .target(ZallyApi.class, zallyUrl);
}
 
Example #4
Source File: DynECTProvider.java    From denominator with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel, DynECTErrorDecoder errorDecoder) {
  return Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .encoder(new GsonEncoder())
      .decoder(new GsonDecoder(Arrays.<TypeAdapter<?>>asList(
                   new TokenAdapter(),
                   new NothingForbiddenAdapter(),
                   new ResourceRecordSetsAdapter(),
                   new ZoneNamesAdapter(),
                   new RecordsByNameAndTypeAdapter()))
      )
      .errorDecoder(errorDecoder)
      .build();
}
 
Example #5
Source File: LoginClient.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch the token from the authentication service.
 *
 *  @param loginURL           Login Url.
 *  @return Auth token.
 */
public static String getAuthToken(final String loginURL) {

    Login client = Feign.builder().client(getClientHostVerificationDisabled())
            .encoder(new GsonEncoder(ModelUtils.GSON))
            .target(Login.class, loginURL);

    Response response = client.login(new AuthRequest(getUsername(), getPassword(), "LOCAL"));

    if (response.status() == OK.code()) {
        Collection<String> headers = response.headers().get(TOKEN_HEADER_NAME);
        return headers.toArray(new String[headers.size()])[0];
    } else {
        throw new TestFrameworkException(TestFrameworkException.Type.LoginFailed, "Exception while " +
                "logging into the cluster. Authentication service returned the following error: "
                + response);
    }
}
 
Example #6
Source File: GitHubExample.java    From feign with Apache License 2.0 6 votes vote down vote up
static GitHub connect() {
  final Decoder decoder = new GsonDecoder();
  final Encoder encoder = new GsonEncoder();
  return Feign.builder()
      .encoder(encoder)
      .decoder(decoder)
      .errorDecoder(new GitHubErrorDecoder(decoder))
      .logger(new Logger.ErrorLogger())
      .logLevel(Logger.Level.BASIC)
      .requestInterceptor(template -> {
        template.header(
            // not available when building PRs...
            // https://docs.travis-ci.com/user/environment-variables/#defining-encrypted-variables-in-travisyml
            "Authorization",
            "token 383f1c1b474d8f05a21e7964976ab0d403fee071");
      })
      .target(GitHub.class, "https://api.github.com");
}
 
Example #7
Source File: PublisherClient.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * PublisherClient constructor - Initialize a PublisherClient instance
 *
 */
public PublisherClient(RequestInterceptor requestInterceptor) {
    Feign.Builder builder = Feign.builder().client(new OkHttpClient(
            org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
            Slf4jLogger())
            .logLevel(Logger.Level.FULL)
            .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
    String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getPublisherEndpoint());

    api = builder.target(APIIndividualApi.class, basePath);
    apis = builder.target(APICollectionApi.class, basePath);
    document = builder.target(DocumentIndividualApi.class, basePath);
    application = builder.target(ApplicationIndividualApi.class, basePath);
    environments = builder.target(EnvironmentCollectionApi.class, basePath);
    subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
    tiers = builder.target(ThrottlingTierCollectionApi.class, basePath);
}
 
Example #8
Source File: StoreClient.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public StoreClient(RequestInterceptor requestInterceptor) {

        Feign.Builder builder = Feign.builder().client(new OkHttpClient(
                org.wso2.carbon.apimgt.integration.client.util.Utils.getSSLClient())).logger(new
                Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .requestInterceptor(requestInterceptor).encoder(new GsonEncoder()).decoder(new GsonDecoder());
        String basePath = Utils.replaceSystemProperty(APIMConfigReader.getInstance().getConfig().getStoreEndpoint());

        apis = builder.target(APICollectionApi.class, basePath);
        individualApi = builder.target(APIIndividualApi.class, basePath);
        applications = builder.target(ApplicationCollectionApi.class, basePath);
        individualApplication = builder.target(ApplicationIndividualApi.class, basePath);
        subscriptions = builder.target(SubscriptionCollectionApi.class, basePath);
        individualSubscription = builder.target(SubscriptionIndividualApi.class, basePath);
        subscriptionMultitpleApi = builder.target(SubscriptionMultitpleApi.class, basePath);
        tags = builder.target(TagCollectionApi.class, basePath);
        individualTier = builder.target(ThrottlingTierIndividualApi.class, basePath);
        tiers = builder.retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(1L), 1))
                .options(new Request.Options(10000, 5000))
                .target(ThrottlingTierCollectionApi.class, basePath);

    }
 
Example #9
Source File: DenominatorDTest.java    From denominator with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void start() throws IOException {
  mock = Denominator.create(new MockProvider());
  server = new DenominatorD(mock);
  int port = server.start();
  client = Feign.builder()
      .encoder(new GsonEncoder())
      .decoder(new GsonDecoder())
      .target(DenominatorDApi.class, "http://localhost:" + port);

  mock.api().basicRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<AData>builder()
      .name("www.denominator.io.")
      .type("A")
      .add(AData.create("192.0.2.1")).build());

  mock.api().weightedRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<CNAMEData>builder()
      .name("www.weighted.denominator.io.")
      .type("CNAME")
      .qualifier("EU-West")
      .weighted(Weighted.create(1))
      .add(CNAMEData.create("www1.denominator.io.")).build());

  mock.api().weightedRecordSetsInZone("denominator.io.").put(ResourceRecordSet.<CNAMEData>builder()
      .name("www.weighted.denominator.io.")
      .type("CNAME")
      .qualifier("US-West")
      .weighted(Weighted.create(1))
      .add(CNAMEData.create("www2.denominator.io.")).build());
}
 
Example #10
Source File: CloudDNSProvider.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
Feign feign(Logger logger, Logger.Level logLevel) {
  return Feign.builder()
      .logger(logger)
      .logLevel(logLevel)
      .encoder(new GsonEncoder())
      .decoder(new GsonDecoder(Arrays.asList(
                   new KeystoneAccessAdapter("rax:dns"),
                   new JobAdapter(),
                   new DomainListAdapter(),
                   new RecordListAdapter()))
      )
      .build();
}
 
Example #11
Source File: BookControllerFeignClientBuilder.java    From tutorials with MIT License 5 votes vote down vote up
private static <T> T createClient(Class<T> type, String uri) {
    return Feign.builder()
        .client(new OkHttpClient())
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())
        .logger(new Slf4jLogger(type))
        .logLevel(Logger.Level.FULL)
        .target(type, uri);
}
 
Example #12
Source File: MarathonClient.java    From marathon-client with Apache License 2.0 5 votes vote down vote up
public static Marathon getInstance(String endpoint) {
	GsonDecoder decoder = new GsonDecoder(ModelUtils.GSON);
	GsonEncoder encoder = new GsonEncoder(ModelUtils.GSON);
	return Feign.builder().encoder(encoder).decoder(decoder)
			.errorDecoder(new MarathonErrorDecoder())
			.requestInterceptor(new MarathonHeadersInterceptor())
			.target(Marathon.class, endpoint);
}
 
Example #13
Source File: OAuthRequestInterceptor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an interceptor that authenticates all requests.
 */
public OAuthRequestInterceptor() {
    String username = APIMConfigReader.getInstance().getConfig().getUsername();
    String password = APIMConfigReader.getInstance().getConfig().getPassword();
    dcrClient = Feign.builder().client(new OkHttpClient(Utils.getSSLClient())).logger(new Slf4jLogger())
            .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username,
                    password))
            .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
            .target(DCRClient.class, Utils.replaceProperties(
                    APIMConfigReader.getInstance().getConfig().getDcrEndpoint()));
}
 
Example #14
Source File: MetronomeClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
public static Metronome getInstance(String endpoint, RequestInterceptor... interceptors) {
    Feign.Builder b = Feign.builder().client(LoginClient.getClientHostVerificationDisabled())
            .logger(new Logger.ErrorLogger())
            .logLevel(Logger.Level.BASIC)
            .encoder(new GsonEncoder(ModelUtils.GSON))
            .decoder(new GsonDecoder(ModelUtils.GSON))
            //max wait period = 5 seconds ; max attempts = 5
            .retryer(new Retryer.Default(SECONDS.toMillis(1), SECONDS.toMillis(5), 5))
            .errorDecoder(new MetronomeErrorDecoder());
    if (interceptors != null) {
        b.requestInterceptors(asList(interceptors));
    }
    b.requestInterceptor(new MetronomeHeadersInterceptor());
    return b.target(Metronome.class, endpoint);
}
 
Example #15
Source File: AuthEnabledMarathonClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
private static Marathon getInstance(String endpoint, RequestInterceptor... interceptors) {
    Feign.Builder b = Feign.builder().client(LoginClient.getClientHostVerificationDisabled())
            .logger(new Logger.ErrorLogger())
            .logLevel(Logger.Level.BASIC)
            .encoder(new GsonEncoder(ModelUtils.GSON))
            .decoder(new GsonDecoder(ModelUtils.GSON))
            .errorDecoder(new MarathonErrorDecoder())
            //max wait period = 5 seconds ; max attempts = 5
            .retryer(new Retryer.Default(SECONDS.toMillis(1), SECONDS.toMillis(5), 5));
    if (interceptors != null) {
        b.requestInterceptors(asList(interceptors));
    }
    b.requestInterceptor(new MarathonHeadersInterceptor());
    return b.target(Marathon.class, endpoint);
}
 
Example #16
Source File: ChronosClient.java    From spring-cloud-deployer-mesos with Apache License 2.0 5 votes vote down vote up
/**
 * The generalized version of the method that allows more in-depth customizations via
 * {@link RequestInterceptor}s.
 *
 * @param endpoint URL for Chronos API
 */
public static Chronos getInstance(String endpoint, RequestInterceptor... interceptors) {
	Builder b = Feign.builder()
			.encoder(new GsonEncoder(AbstractModel.GSON))
			.decoder(new MultiDecoder())
			.errorDecoder(new ChronosErrorDecoder());
	if (interceptors != null) {
		b.requestInterceptors(asList(interceptors));
	}
	b.requestInterceptor(new ChronosHeadersInterceptor());
	return b.target(Chronos.class, endpoint);
}
 
Example #17
Source File: RibbonMarathonClient.java    From spring-cloud-marathon with MIT License 5 votes vote down vote up
public Marathon build() {
    if (null == listOfServers) {
        if (!StringUtils.isEmpty(token)) {
            return getInstanceWithTokenAuth(baseEndpoint, token);
        } else if (!StringUtils.isEmpty(username)) {
            return getInstanceWithBasicAuth(baseEndpoint, username, password);
        } else {
            return getInstance(baseEndpoint);
        }
    } else {
        setMarathonRibbonProperty("listOfServers", listOfServers);
        setMarathonRibbonProperty("OkToRetryOnAllOperations", Boolean.TRUE.toString());
        setMarathonRibbonProperty("MaxAutoRetriesNextServer", maxRetryCount);
        setMarathonRibbonProperty("ConnectTimeout", connectionTimeout);
        setMarathonRibbonProperty("ReadTimeout", readTimeout);

        Feign.Builder builder = Feign.builder()
                .client(RibbonClient.builder().lbClientFactory(new MarathonLBClientFactory()).build())
                .encoder(new GsonEncoder(ModelUtils.GSON))
                .decoder(new GsonDecoder(ModelUtils.GSON))
                .errorDecoder(new MarathonErrorDecoder());

        if (!StringUtils.isEmpty(token)) {
            builder.requestInterceptor(new TokenAuthRequestInterceptor(token));
        }
        else if (!StringUtils.isEmpty(username)) {
            builder.requestInterceptor(new BasicAuthRequestInterceptor(username,password));
        }

        builder.requestInterceptor(new MarathonHeadersInterceptor());

        return builder.target(Marathon.class, DEFAULT_MARATHON_ENDPOINT);
    }
}
 
Example #18
Source File: DCOSClient.java    From marathon-client with Apache License 2.0 5 votes vote down vote up
private static DCOS buildInstance(String endpoint, Consumer<Feign.Builder> customize) {
    GsonDecoder decoder = new GsonDecoder(ModelUtils.GSON);
    GsonEncoder encoder = new GsonEncoder(ModelUtils.GSON);

    Feign.Builder builder = Feign.builder()
                                 .encoder(encoder)
                                 .decoder(decoder)
                                 .errorDecoder(new DCOSErrorDecoder());
    customize.accept(builder);
    builder.requestInterceptor(new DCOSAPIInterceptor());

    return builder.target(DCOS.class, endpoint);
}
 
Example #19
Source File: AMDefaultKeyManagerImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {

    this.configuration = configuration;

    String consumerKey = (String) configuration.getParameter(APIConstants.KEY_MANAGER_CONSUMER_KEY);
    String consumerSecret = (String) configuration.getParameter(APIConstants.KEY_MANAGER_CONSUMER_SECRET);
    String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);

    String dcrEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
        dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
    } else {
        dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim()).concat("/api/identity/oauth2/dcr/v1.1/register");
    }
    String tokenEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
        tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
    } else {
        tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
                "/oauth2/token");
    }
    addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
    String revokeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
        revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
    } else {
        revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
                "/oauth2/revoke");
    }
    String scopeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
        scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
    } else {
        scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim())
                .concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
    }
    String introspectionEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
        introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
    } else {
        introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
                .concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
    }
    accessTokenGenerator = new AccessTokenGenerator(tokenEndpoint, revokeEndpoint, consumerKey, consumerSecret);

    dcrClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .target(DCRClient.class, dcrEndpoint);
    authClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .errorDecoder(new KMClientErrorDecoder())
            .encoder(new FormEncoder())
            .target(AuthClient.class, tokenEndpoint);

    introspectionClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .encoder(new FormEncoder())
            .target(IntrospectionClient.class, introspectionEndpoint);
    scopeClient = Feign.builder()
            .client(new OkHttpClient())
            .encoder(new GsonEncoder())
            .decoder(new GsonDecoder())
            .logger(new Slf4jLogger())
            .requestInterceptor(new BearerInterceptor(accessTokenGenerator))
            .errorDecoder(new KMClientErrorDecoder())
            .target(ScopeClient.class, scopeEndpoint);
}
 
Example #20
Source File: JsonEncoderTest.java    From triplea with GNU General Public License v3.0 4 votes vote down vote up
private static RequestTemplate encodeWithGson(final SampleObject sampleObject) {
  final GsonEncoder gsonEncoder = new GsonEncoder();
  final RequestTemplate templateForGsonEncoding = new RequestTemplate();
  gsonEncoder.encode(sampleObject, SampleObject.class, templateForGsonEncoding);
  return templateForGsonEncoding;
}