com.netflix.util.Pair Java Examples
The following examples show how to use
com.netflix.util.Pair.
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: RestClient.java From s2g-zuul with MIT License | 6 votes |
@Override protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(HttpRequest task) { URI theUrl = task.getUri(); boolean isSecure = getBooleanFromConfig(task.getOverrideConfig(), CommonClientConfigKey.IsSecure, this.isSecure); String scheme = theUrl.getScheme(); if (scheme != null) { isSecure = scheme.equalsIgnoreCase("https"); } int port = theUrl.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<String, Integer>(scheme, port); }
Example #2
Source File: CorsServiceTest.java From heimdall with Apache License 2.0 | 6 votes |
@Test public void executeCORSPreFilterWithMethodOption() { request.setMethod(HttpMethod.OPTIONS.name()); this.ctx.setRequest(request); this.ctx.setResponse(response); this.corsInterceptorService.executeCorsPreFilter(cors); List<Pair<String, String>> zuulResponseHeaders = this.ctx.getZuulResponseHeaders(); AtomicInteger count = new AtomicInteger(); zuulResponseHeaders.forEach(pair-> { String value = cors.get(pair.first()); if (value != null) { if (value.equals(pair.second())) { count.getAndIncrement(); } } }); Assert.assertEquals(count.get(), cors.size()); }
Example #3
Source File: SlashFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void proxyIsEmpty() throws Exception { final RequestContext ctx = RequestContext.getCurrentContext(); ctx.set(PROXY_KEY, ""); this.filter.run(); Boolean isLocation = false; List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); if (zuulResponseHeaders != null) { for (Pair<String, String> header : zuulResponseHeaders) { if (header.first().equals("Location")) isLocation = true; } } assertEquals(false, isLocation); assertEquals(500, ctx.getResponseStatusCode()); }
Example #4
Source File: SlashFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void proxyIsNull() throws Exception { final RequestContext ctx = RequestContext.getCurrentContext(); ctx.set(PROXY_KEY, null); this.filter.run(); Boolean isLocation = false; List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); if (zuulResponseHeaders != null) { for (Pair<String, String> header : zuulResponseHeaders) { if (header.first().equals("Location")) isLocation = true; } } assertEquals(false, isLocation); assertEquals(500, ctx.getResponseStatusCode()); }
Example #5
Source File: SlashFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void proxyEndsWithSlash() throws Exception { final RequestContext ctx = RequestContext.getCurrentContext(); ctx.set(PROXY_KEY, "ui/service/"); this.filter.run(); String location = ""; List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); if (zuulResponseHeaders != null) { for (Pair<String, String> header : zuulResponseHeaders) { if (header.first().equals("Location")) location = header.second(); } } assertEquals("/ui/service/", location); assertEquals(302, ctx.getResponseStatusCode()); }
Example #6
Source File: SlashFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void proxyStartsWithSlash() throws Exception { final RequestContext ctx = RequestContext.getCurrentContext(); ctx.set(PROXY_KEY, "/ui/service"); this.filter.run(); String location = ""; List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); if (zuulResponseHeaders != null) { for (Pair<String, String> header : zuulResponseHeaders) { if (header.first().equals("Location")) location = header.second(); } } assertEquals("/ui/service/", location); assertEquals(302, ctx.getResponseStatusCode()); }
Example #7
Source File: BaseFilter.java From convergent-ui with Apache License 2.0 | 6 votes |
protected MimeType getMimeType(RequestContext context) { List<Pair<String, String>> headers = context.getZuulResponseHeaders(); String contentType = null; for (Pair<String, String> pair : headers) { if ("content-type".equalsIgnoreCase(pair.first())) { contentType = pair.second(); break; } } if (contentType != null) { MimeType type = MimeType.valueOf(contentType); return type; } return null; }
Example #8
Source File: RestClient.java From ribbon with Apache License 2.0 | 6 votes |
@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); }
Example #9
Source File: PageRedirectionFilterTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void sameServerAndUrlMatched() throws Exception { RoutedService currentService = new RoutedService("ui", "ui", "/"); RoutedServices routedServices = new RoutedServices(); routedServices.addRoutedService(currentService); this.filter.addRoutedServices(SERVICE_ID, routedServices); when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList( new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true) )); response.setStatus(302); String relativePath = "/some/path/login.html"; String location = mockLocationSameServer(relativePath); final RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulResponseHeader(LOCATION, location); this.filter.run(); Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders() .stream() .filter(stringPair -> LOCATION.equals(stringPair.first())) .findFirst(); verifyLocationUpdatedSameServer(locationHeader.map(Pair::second).orElse(null), location, "/" + currentService.getGatewayUrl() + "/" + SERVICE_ID + relativePath); }
Example #10
Source File: SendResponse.java From s2g-zuul with MIT License | 6 votes |
private void addResponseHeaders() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = ctx.getResponse(); for (Pair<String, String> p : ctx.getZuulResponseHeaders()) { servletResponse.addHeader(p.first(), p.second()); } Integer contentLength = ctx.getOriginContentLength(); // only inserts Content-Length if origin provides it and origin response // is not gzipped if (CONTENT_LENGTH.get()) { if (contentLength != null && !ctx.getResponseGZipped()) servletResponse.setContentLength(contentLength); } }
Example #11
Source File: LoadBalancerContext.java From ribbon with Apache License 2.0 | 6 votes |
/** * Derive scheme and port from a partial URI. For example, for HTTP based client, the URI with * only path "/" should return "http" and 80, whereas the URI constructed with scheme "https" and * path "/" should return "https" and 443. * This method is called by {@link #getServerFromLoadBalancer(java.net.URI, Object)} and * {@link #reconstructURIWithServer(Server, java.net.URI)} methods to get the complete executable URI. */ protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(URI uri) { boolean isSecure = false; 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<String, Integer>(scheme, port); }
Example #12
Source File: ElasticSearchSink.java From suro with Apache License 2.0 | 6 votes |
@VisibleForTesting protected Pair<HttpRequest, List<Message>> createBulkRequest(List<Message> msgList) { List<Message> msgListPayload = new LinkedList<>(); StringBuilder sb = new StringBuilder(); for (Message m : msgList) { String indexRequest = createIndexRequest(m); if (indexRequest != null) { sb.append(indexRequest); msgListPayload.add(m); } } return new Pair<>( HttpRequest.newBuilder() .verb(HttpRequest.Verb.POST) .uri("/_bulk") .setRetriable(true) .entity(sb.toString()).build(), msgListPayload); }
Example #13
Source File: Server.java From ribbon with Apache License 2.0 | 5 votes |
static Pair<String, Integer> getHostPort(String id) { if (id != null) { String host = null; int port = 80; if (id.toLowerCase().startsWith("http://")) { id = id.substring(7); port = 80; } else if (id.toLowerCase().startsWith("https://")) { id = id.substring(8); port = 443; } if (id.contains("/")) { int slash_idx = id.indexOf("/"); id = id.substring(0, slash_idx); } int colon_idx = id.indexOf(':'); if (colon_idx == -1) { host = id; // default } else { host = id.substring(0, colon_idx); try { port = Integer.parseInt(id.substring(colon_idx + 1)); } catch (NumberFormatException e) { throw e; } } return new Pair<String, Integer>(host, port); } else { return null; } }
Example #14
Source File: Server.java From ribbon with Apache License 2.0 | 5 votes |
static public String normalizeId(String id) { Pair<String, Integer> hostPort = getHostPort(id); if (hostPort == null) { return null; } else { return hostPort.first() + ":" + hostPort.second(); } }
Example #15
Source File: RestClient.java From ribbon with Apache License 2.0 | 5 votes |
@Override protected Pair<String, Integer> deriveHostAndPortFromVipAddress(String vipAddress) throws URISyntaxException, ClientException { if (!vipAddress.contains("http")) { vipAddress = "http://" + vipAddress; } return super.deriveHostAndPortFromVipAddress(vipAddress); }
Example #16
Source File: Server.java From ribbon with Apache License 2.0 | 5 votes |
public void setId(String id) { Pair<String, Integer> hostPort = getHostPort(id); if (hostPort != null) { this.id = hostPort.first() + ":" + hostPort.second(); this.host = hostPort.first(); this.port = hostPort.second(); this.scheme = getScheme(id); } else { this.id = null; } }
Example #17
Source File: ProxyRedirectFilter.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 5 votes |
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); for (Pair<String, String> zuulResponseHeader : zuulResponseHeaders) { if ("Location".equalsIgnoreCase(zuulResponseHeader.first())) { zuulResponseHeader.setSecond(ctx.get(REDIRECT_TO_URL).toString()); break; } } return null; }
Example #18
Source File: ProxyRedirectFilter.java From spring-cloud-netflix-zuul-websocket with Apache License 2.0 | 5 votes |
@Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); boolean isRedirect = ctx.getResponseStatusCode() == 301 || ctx.getResponseStatusCode() == 302; if (!isRedirect) return false; boolean hasCorrectLocation = false; List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); for (Pair<String, String> zuulResponseHeader : zuulResponseHeaders) { if ("Location".equalsIgnoreCase(zuulResponseHeader.first())) { HttpServletRequest request = ctx.getRequest(); String path = urlPathHelper.getPathWithinApplication(request); Route route = routeLocator.getMatchingRoute(path); UriComponents redirectTo = ServletUriComponentsBuilder .fromHttpUrl(zuulResponseHeader.second()).build(); UriComponents routeLocation = ServletUriComponentsBuilder .fromHttpUrl(route.getLocation()).build(); if (redirectTo.getHost().equalsIgnoreCase(routeLocation.getHost()) && redirectTo.getPort() == routeLocation.getPort()) { String toLocation = ServletUriComponentsBuilder .fromHttpUrl(zuulResponseHeader.second()) .host(request.getServerName()) .port(request.getServerPort()) .replacePath( buildRoutePath(route, zuulResponseHeader.second())) .build().toUriString(); ctx.put(REDIRECT_TO_URL, toLocation); hasCorrectLocation = true; break; } } } return hasCorrectLocation; }
Example #19
Source File: S3Consumer.java From suro with Apache License 2.0 | 5 votes |
@VisibleForTesting protected Map<String, Object> parseMessage(Pair<String, String> msg) throws IOException { Map<String, Object> msgContainer = jsonMapper.readValue(msg.second(), typeReference); if (!(msgContainer.get("Message") instanceof Map)) { return jsonMapper.readValue(msgContainer.get("Message").toString(), typeReference); } else { return (Map<String, Object>) msgContainer.get("Message"); } }
Example #20
Source File: S3Consumer.java From suro with Apache License 2.0 | 5 votes |
private Runnable createEmptyRunnable(final Pair<String, String> msg) { return new Runnable() { @Override public void run() { log.error("invalid msg: " + msg.second()); } }; }
Example #21
Source File: SQSNotice.java From suro with Apache License 2.0 | 5 votes |
@Override public Pair<String, String> peek() { ReceiveMessageRequest request = new ReceiveMessageRequest() .withQueueUrl(queueUrls.get(0)) .withMaxNumberOfMessages(1); try { ReceiveMessageResult result = sqsClient.receiveMessage(request); if (!result.getMessages().isEmpty()) { Message msg = result.getMessages().get(0); recvMessageCount.incrementAndGet(); if (enableBase64Encoding) { return new Pair<String, String>( msg.getReceiptHandle(), new String( Base64.decodeBase64(msg.getBody().getBytes()), Charsets.UTF_8)); } else { return new Pair<String, String>( msg.getReceiptHandle(), msg.getBody()); } } else { return null; } } catch (Exception e) { log.error("Exception while recving SQS notice: " + e.getMessage(), e); return null; } }
Example #22
Source File: RestClient.java From s2g-zuul with MIT License | 5 votes |
@Override protected Pair<String, Integer> deriveHostAndPortFromVipAddress(String vipAddress) throws URISyntaxException, ClientException { if (!vipAddress.contains("http")) { vipAddress = "http://" + vipAddress; } return super.deriveHostAndPortFromVipAddress(vipAddress); }
Example #23
Source File: CORSInterceptorService.java From heimdall with Apache License 2.0 | 5 votes |
private void addHeadersToResponseOptions(Map<String, String> cors) { RequestContext ctx = RequestContext.getCurrentContext(); List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders(); List<String> headersFromResponse = zuulResponseHeaders.stream().map(Pair::first).collect(Collectors.toList()); cors.entrySet() .stream() .filter(entry -> !headersFromResponse.contains(entry.getKey())) .forEach(entry -> ctx.addZuulResponseHeader(entry.getKey(), entry.getValue())); }
Example #24
Source File: LocationHeaderRewritingFilter.java From pulsar-manager with Apache License 2.0 | 5 votes |
private Pair<String, String> locationHeader(RequestContext ctx) { if (ctx.getZuulResponseHeaders() != null) { for (Pair<String, String> pair : ctx.getZuulResponseHeaders()) { if (pair.first().equals(LOCATION_HEADER)) { return pair; } } } return null; }
Example #25
Source File: RequestContext.java From s2g-zuul with MIT License | 5 votes |
/** * returns the current response header list * * @return a List<Pair<String, String>> of response headers */ public List<Pair<String, String>> getZuulResponseHeaders() { if (get("zuulResponseHeaders") == null) { List<Pair<String, String>> zuulRequestHeaders = new ArrayList<Pair<String, String>>(); putIfAbsent("zuulResponseHeaders", zuulRequestHeaders); } return (List<Pair<String, String>>) get("zuulResponseHeaders"); }
Example #26
Source File: RequestContext.java From s2g-zuul with MIT License | 5 votes |
/** * the Origin response headers * * @return the List<Pair<String, String>> of headers sent back from the * origin */ public List<Pair<String, String>> getOriginResponseHeaders() { if (get("originResponseHeaders") == null) { List<Pair<String, String>> originResponseHeaders = new ArrayList<Pair<String, String>>(); putIfAbsent("originResponseHeaders", originResponseHeaders); } return (List<Pair<String, String>>) get("originResponseHeaders"); }
Example #27
Source File: DebugHeader.java From s2g-zuul with MIT License | 5 votes |
public void addStandardResponseHeaders(HttpServletRequest req, HttpServletResponse res) { RequestContext context = RequestContext.getCurrentContext(); List<Pair<String, String>> headers = context.getZuulResponseHeaders(); headers.add(new Pair("X_ZUUL", "mobile_gateway")); // TODO, get zuul instance id headers.add(new Pair("X_ZUUL_INSTANCE", "unknown")); headers.add(new Pair("CONNECTION", "KEEP_ALIVE")); headers.add(new Pair("X_ZUUL_FILTER_EXECUTION_STATUS", context.getFilterExecutionSummary().toString())); headers.add(new Pair("X_ORIGINATING_URL", getOriginatingURL())); if (INCLUDE_ROUTE_URL_HEADER.get()) { String routeUrl = context.getRouteUrl().toString(); if (routeUrl != null && !routeUrl.isEmpty()) { headers.add(new Pair("x-zuul-route-url", routeUrl)); } } //Support CROS headers.add(new Pair("Access-Control-Allow-Origin", "*")); headers.add(new Pair("Access-Control-Allow-Headers","Content-Type, Accept")); headers.add(new Pair("x-zuul-remote-call-cost", String.valueOf(RequestContext.getCurrentContext().get("remoteCallCost")))); if (!context.errorHandled() && context.getResponseStatusCode() >= 400) { headers.add(new Pair("X_ZUUL_ERROR_CAUSE", "Error from Origin")); } }
Example #28
Source File: PageRedirectionFilter.java From api-layer with Eclipse Public License 2.0 | 5 votes |
/** * When the filter runs, it first finds the Location url in cache. If matched url can be found in cache, it then replaces Location with the matched url. * If not, the filter will find the matched url in Discovery Service. If matched url can be found in Discovery Service, the filter will put the matched * url to cache, and replace Location with the matched url * * @return null */ @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); Optional<Pair<String, String>> locationHeader = context.getZuulResponseHeaders() .stream() .filter(stringPair -> LOCATION.equals(stringPair.first())) .findFirst(); if (locationHeader.isPresent()) { String location = locationHeader.get().second(); //find matched url in cache String transformedUrl = foundUrlInTable(location); if (transformedUrl != null) { transformLocation(locationHeader.get(), transformedUrl); } else { //find matched url in Discovery Service Optional<String> transformedUrlOp = getMatchedUrlFromDS(location); if (transformedUrlOp.isPresent()) { transformedUrl = transformedUrlOp.get(); //Put matched url to cache routeTable.put(location, transformedUrl); transformLocation(locationHeader.get(), transformedUrl); } } } return null; }
Example #29
Source File: PageRedirectionFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void sameServerAndUrlNotMatched() { String serviceUrl = "/discoverableclient/api/v1"; RoutedService currentService = new RoutedService("api-v1", "api/v1", serviceUrl); RoutedServices routedServices = new RoutedServices(); routedServices.addRoutedService(currentService); this.filter.addRoutedServices(SERVICE_ID, routedServices); when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList( new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true) )); response.setStatus(304); String relativePath = "/some/path/login.html"; String location = mockLocationSameServer(relativePath); final RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulResponseHeader(LOCATION, location); this.filter.run(); Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders() .stream() .filter(stringPair -> LOCATION.equals(stringPair.first())) .findFirst(); verifyLocationNotUpdated(locationHeader.map(Pair::second).orElse(null), location); }
Example #30
Source File: PageRedirectionFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void hostRegisteredAndUrlMatched() throws Exception { //route for current service RoutedService currentService = new RoutedService("ui", "ui", "/"); RoutedServices routedServices = new RoutedServices(); routedServices.addRoutedService(currentService); this.filter.addRoutedServices(SERVICE_ID, routedServices); //route for other service String serviceUrl = "/discoverableclient/api/v1"; RoutedService otherService = new RoutedService("ui-v1", "ui/v1", serviceUrl); RoutedServices otherRoutedServices = new RoutedServices(); otherRoutedServices.addRoutedService(otherService); this.filter.addRoutedServices(OTHER_SERVICE_ID, otherRoutedServices); when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList( new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true) )); when(discoveryClient.getInstances(OTHER_SERVICE_ID)).thenReturn(Collections.singletonList( new DefaultServiceInstance(OTHER_SERVICE_ID, OTHER_SERVICE_SERVER_HOST, OTHER_SERVICE_SERVER_PORT, true) )); when(discoveryClient.getServices()).thenReturn(Arrays.asList(SERVICE_ID, OTHER_SERVICE_ID)); response.setStatus(307); String relativePath = "/some/path/login.html"; String location = mockLocationDSServer(serviceUrl + relativePath); final RequestContext ctx = RequestContext.getCurrentContext(); ctx.addZuulResponseHeader(LOCATION, location); this.filter.run(); Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders() .stream() .filter(stringPair -> LOCATION.equals(stringPair.first())) .findFirst(); this.verifyLocationUpdatedSameServer(locationHeader.map(Pair::second).orElse(null), location, "/" + otherService.getGatewayUrl() + "/" + OTHER_SERVICE_ID + relativePath); }