public static TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<ClientFilter> additionalFilters ) { final TransportClientFactory jerseyFactory = JerseyEurekaHttpClientFactory.create( clientConfig, additionalFilters, null, null); final TransportClientFactory metricsFactory = MetricsCollectingEurekaHttpClient.createFactory(jerseyFactory); return new TransportClientFactory() { @Override public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) { return metricsFactory.newClient(serviceUrl); } @Override public void shutdown() { metricsFactory.shutdown(); jerseyFactory.shutdown(); } }; }
private static Client buildClient() { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(ByteStringMessageBodyWriter.class); Client client = Client.create(config); client.setFollowRedirects(true); client.addFilter(new ClientFilter() { @Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { log.debug("Making request {} {}", cr.getMethod(), cr.getURI()); ClientResponse response = getNext().handle(cr); return response; } }); return client; }
@Before public void init() throws Exception { Properties properties = new Properties(); wsBaseUrl = new URIBuilder(getBaseURI()).setPath(contextPath).toString(); properties.put("occurrence.ws.url", wsBaseUrl); properties.put("httpTimeout", HTTP_TO); Injector clientInjector = Guice.createInjector(new OccurrenceWsClientModule(properties), new AbstractModule() { @Override protected void configure() { //ClientFilter is required by the OccurrenceDownloadClient for authentication bind(ClientFilter.class).toInstance(Mockito.mock(ClientFilter.class)); } }); client = clientInjector.getInstance(OccurrenceService.class); }
/** * * @param config config REST Client configuration * @param handler handler Jersey client handler. Useful when plugging in various http client interaction modules (e.g. ribbon) * @param filters Chain of client side filters to be applied per request */ public TaskClient(ClientConfig config, ClientHandler handler, ClientFilter...filters) { super(config, handler); for(ClientFilter filter : filters) { super.client.addFilter(filter); } }
/** * * @param config config REST Client configuration * @param handler handler Jersey client handler. Useful when plugging in various http client interaction modules (e.g. ribbon) * @param filters Chain of client side filters to be applied per request */ public WorkflowClient(ClientConfig config, ClientHandler handler, ClientFilter...filters) { super(config, handler); for(ClientFilter filter : filters) { super.client.addFilter(filter); } }
public RemoteInstanceRequestClientImpl(RemoteConnectionConfiguration configuration) { client = Client.create(); client.setConnectTimeout(configuration.getConnectionTimeoutMs()); client.setReadTimeout(configuration.getReadTimeoutMs()); for ( ClientFilter filter : configuration.getFilters() ) { client.addFilter(filter); } }
public EurekaTransport createTransport() { TransportClientFactory transportClientFactory = newTransportClientFactory(clientConfig, Collections.<ClientFilter>emptyList()); EurekaTransportConfig transportConfig = clientConfig.getTransportConfig(); ClosableResolver<AwsEndpoint> bootstrapResolver = EurekaHttpClients.newBootstrapResolver( clientConfig, transportConfig, transportClientFactory, null, (stalenessThreshold, timeUnit) -> { long thresholdInMs = TimeUnit.MILLISECONDS.convert(stalenessThreshold, timeUnit); long delay = eurekaClient.getLastSuccessfulRegistryFetchTimePeriod(); if (delay > thresholdInMs) { log.info("Local registry is too stale for local lookup. Threshold:{}, actual:{}", thresholdInMs, delay); return null; } else { return eurekaClient.getApplications(); } } ); EurekaHttpClientFactory httpClientFactory; try { httpClientFactory = EurekaHttpClients.registrationClientFactory( bootstrapResolver, transportClientFactory, transportConfig ); } catch (Exception e) { log.warn("Experimental transport initialization failure", e); throw new RuntimeException(e); } return new EurekaTransport(httpClientFactory, httpClientFactory.newClient(), transportClientFactory, bootstrapResolver); }
/** * Goes over all GitHub pages and return all pages union. * * @param webResource of first page * @param entityType type of entities * @return union */ protected <T> List<T> getAll(WebResource webResource, Class<T[]> entityType, ClientFilter filter) { List<T> result = new LinkedList<T>(); WebResource cursor = webResource; do { if (filter != null) { cursor.addFilter(filter); } WebResource.Builder builder = cursor.accept(MediaType.APPLICATION_JSON_TYPE); ClientResponse clientResponse = builder.get(ClientResponse.class); if (clientResponse.getStatus() < 300) { result.addAll(Arrays.asList(clientResponse.getEntity(entityType))); LinkHeaders linkHeaders = getLinks(clientResponse); LinkHeader nextLink = linkHeaders.getLink("next"); URI nextPage = nextLink != null ? nextLink.getUri() : null; cursor = nextPage != null ? client.resource(nextPage) : null; } else { throw new UniformInterfaceException(clientResponse); } } while (cursor != null); return result; }
protected JerseyClient(Client client, String baseUrl, List<ClientFilter> filters, int connectTimeout, int readTimeout) { this.baseUrl = baseUrl; this.filters = filters; this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; if (client != null) { this.client = client; } else { this.client = createClient(); initializeClient(); } }
@Test public void client_applies_filter_and_base_url_to_resource() { Client client = mock(Client.class); WebResource resource = mock(WebResource.class); when(client.resource("base")).thenReturn(resource); HeaderProcessor processor = mock(HeaderProcessor.class); JerseyClient c = new JerseyClient(client, "base", new ArrayList<ClientFilter>(), 10, 10).filtered(processor); WebResource r = c.resource(); assertSame(resource, r); ArgumentCaptor<HeaderProcessorClientFilter> filterArg = ArgumentCaptor.forClass(HeaderProcessorClientFilter.class); verify(resource).addFilter(filterArg.capture()); assertSame(processor, filterArg.getValue().processor); }
@Test public void creating_client_applies_connection_and_read_timeout() { final Client client = mock(Client.class); new JerseyClient(null, "base", new ArrayList<ClientFilter>(), 1, 2) { protected Client createClient() { return client; }; }; verify(client).setConnectTimeout(1); verify(client).setReadTimeout(2); }
public RemoteConnectionConfiguration() { this(Lists.<ClientFilter>newArrayList(), DEFAULT_CONNECTION_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS); }
public RemoteConnectionConfiguration(Collection<ClientFilter> filters) { this(filters, DEFAULT_CONNECTION_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS); }
public RemoteConnectionConfiguration(Collection<ClientFilter> filters, int connectionTimeoutMs, int readTimeoutMs) { this.filters = ImmutableList.copyOf(Preconditions.checkNotNull(filters, "filters cannot be null")); this.connectionTimeoutMs = connectionTimeoutMs; this.readTimeoutMs = readTimeoutMs; }
public Collection<ClientFilter> getFilters() { return filters; }
public boolean isFilterPresent(ClientFilter clientFilter) { return clientFilters.contains(clientFilter); }
public void addFilter(ClientFilter clientFilter) { client.addFilter(clientFilter); clientFilters.add(clientFilter); }
/** Creates a new JerseyClient to the given base URL */ public static JerseyClient to(String baseUrl) { return new JerseyClient(null, baseUrl, new ArrayList<ClientFilter>(), 10000, 60000); }
/** * Returns a new JerseyClient that will apply the given header processor at the end of the chain. */ public JerseyClient filtered(final HeaderProcessor headerProcessor) { ArrayList<ClientFilter> f = new ArrayList<>(filters); f.add(new HeaderProcessorClientFilter(headerProcessor)); return new JerseyClient(client, baseUrl, f, connectTimeout, readTimeout); }
@Override public void setAdditionalFilters(Collection<ClientFilter> additionalFilters) { additionalFilters = new LinkedHashSet<>(additionalFilters); this.additionalFilters = additionalFilters; super.setAdditionalFilters(additionalFilters); }
public Collection<ClientFilter> getAdditionalFilters() { return this.additionalFilters; }
@RequestMapping(value="/admin/importGeonames", method=RequestMethod.POST) @ResponseBody public String importGeonames() { List<Place> places = placeDao.findByProvenanceNotAndIdsContextAndDeletedIsFalse("geonames","geonames"); logger.debug("found {} places with geonames-id and no location", places.size()); ClientConfig config = new DefaultClientConfig(); config.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(config); WebResource api = client.resource(geonamesSolrUri).path("select").queryParam("wt", "json").queryParam("rows", "1000"); api.addFilter(new ClientFilter() { @Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { ClientResponse response = getNext().handle(request); response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); return response; } }); int count = 0; for (Place place : places) { String geonamesId = place.getIdentifier("geonames"); if (!geonamesId.matches("\\d*")) { logger.warn("invalid geonames identifier \"" + geonamesId + "\" for place with id " + place.getId()); continue; } ObjectNode node = api.queryParam("q", String.format("seriennummer:%s", geonamesId)) .get(ObjectNode.class); if (node.get("response").get("numFound").asInt() > 0) { logger.debug("found {} candidates.", node.get("response").get("numFound")); JsonNode entries = node.get("response").get("docs"); boolean updated = false; List<String> languages = Arrays.asList(languagesHelper.getLanguages()); for (JsonNode entry : entries) { if (entry.has("longitude") && entry.has("latitude")) { if (place.getPrefLocation() == null || ((place.getPrefLocation().getCoordinates() == null || place.getPrefLocation().getCoordinates().length == 0) && place.getPrefLocation().getShape() == null)) { logger.debug("found coordinates in doc: {}", entry); place.setPrefLocation(new Location(entry.get("longitude").get(0).asDouble(), entry.get("latitude").get(0).asDouble())); updated = true; } } if (entry.has("alternateName")) { String altName = entry.get("alternateName").get(0).asText(); String lang = entry.get("isoLanguage").get(0).asText(); try { String iso3Lang = new Locale(lang).getISO3Language(); logger.debug("found alternatename '{}' for language '{}'", altName, iso3Lang); // skip languages that are not configured if (!languages.contains(iso3Lang)) { continue; } place.addName(new PlaceName(altName, iso3Lang)); } catch (MissingResourceException e) { logger.warn(e.getMessage()); } updated = true; } } if (updated) { count++; place.addProvenance("geonames"); placeDao.save(place); } } } return String.format("OK: imported data for %s places", count); }
public static void setup(String user, String password) { filters = new ClientFilter[] { new HTTPBasicAuthFilter(user, password) }; }
@Override public void authenticateClient(Client client) { client.setFollowRedirects(false); WebResource webResource; try { webResource = client.resource(new URI(endpoint)); } catch (URISyntaxException e) { throw new DrupalException("Drupal URI Invalid", e); } client.addFilter(new ClientFilter() { private ArrayList<Object> cookies; @Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { if (cookies != null) { request.getHeaders().put(HttpHeaders.COOKIE, cookies); } ClientResponse response = getNext().handle(request); if (response.getCookies() != null) { if (cookies == null) { cookies = new ArrayList<Object>(); } cookies.addAll(response.getCookies()); } return response; } }); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("name", user); formData.add("pass", password); formData.add("form_id", "user_login_form"); webResource.type(MediaType.APPLICATION_FORM_URLENCODED) .post(ClientResponse.class, formData); }
/** * @param resource webapplication root url */ @Inject public OccurrenceDownloadWsClient(WebResource resource, @Nullable ClientFilter authFilter) { super(Download.class, resource.path(Constants.OCCURRENCE_DOWNLOAD_PATH), authFilter); mapper.getSerializationConfig().addMixInAnnotations(Download.class, LicenseMixin.class); }
/** * Sets up a registry DatasetService client avoiding the use of guice as our gbif jackson libraries clash with the * hadoop versions. * Sets up an http client with a one minute timeout and http support only. */ public DatasetService setupDatasetService(String uri) { return new DatasetWsClient(httpClient.resource(uri), injector.getInstance(ClientFilter.class)); }
/** * Sets up a DatasetOccurrenceDownloadUsageService client avoiding the use of guice as our gbif jackson libraries * clash with the hadoop versions. * Sets up an http client with a one minute timeout and http support only. */ public DatasetOccurrenceDownloadUsageService setupDatasetUsageService(String uri) { return new DatasetOccurrenceDownloadUsageWsClient(httpClient.resource(uri), injector.getInstance(ClientFilter.class)); }
/** * Sets up a OccurrenceDownloadService client avoiding the use of guice as our gbif jackson libraries * clash with the hadoop versions. * Sets up an http client with a one minute timeout and http support only. */ public OccurrenceDownloadService setupOccurrenceDownloadService(String uri) { return new OccurrenceDownloadWsClient(httpClient.resource(uri), injector.getInstance(ClientFilter.class)); }