/** * {@inheritDoc} */ @Override public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) throws IOException { final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY); final long id = requestId != null ? (Long) requestId : _id.incrementAndGet(); StringBuilder b = (StringBuilder) requestContext.getProperty(LOGGER_BUFFER_PROPERTY); if (b == null) { b = new StringBuilder(); requestContext.setProperty(LOGGER_BUFFER_PROPERTY, b); } printResponseLine(b, "Client response received", id, responseContext.getStatus()); printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders()); if (printEntity && responseContext.hasEntity() && isSupportPrintType(responseContext.getMediaType())) { responseContext.setEntityStream(logInboundEntity(b, responseContext.getEntityStream(), MessageUtils.getCharset(responseContext.getMediaType()))); } log(b); }
@Override public void filter( final ClientRequestContext requestContext, final ClientResponseContext responseContext ) throws IOException { if ( Response.Status.UNAUTHORIZED.getStatusCode() == responseContext.getStatus() ) { final List<Object> headers = requestContext.getHeaders().get( HttpHeaders.AUTHORIZATION ); if ( null == headers ) { return; } for ( final Object header : headers ) { if ( header instanceof String ) { final String headerValue = (String) header; if ( headerValue.startsWith( AUTH_HEADER_PREFIX ) ) { final String token = headerValue.substring( AUTH_HEADER_PREFIX.length() ); _keycloak.invalidate( token ); } } } } }
@Override public void filter(ClientRequestContext requestContext) throws IOException { logger.info("getAcceptableLanguages : " + requestContext.getAcceptableLanguages()); logger.info("getClient : " + requestContext.getClient()); logger.info("getConfiguration : " + requestContext.getConfiguration()); logger.info("getCookies : " + requestContext.getCookies()); logger.info("getDate : " + requestContext.getDate()); logger.info("getEntity : " + requestContext.getEntity()); logger.info("getEntityAnnotations : " + requestContext.getEntityAnnotations()); logger.info("getEntityClass : " + requestContext.getEntityClass()); logger.info("getEntityStream : " + requestContext.getEntityStream()); logger.info("getEntityType : " + requestContext.getEntityType()); logger.info("getHeaders : " + requestContext.getHeaders()); logger.info("getLanguage : " + requestContext.getLanguage()); logger.info("getMediaType : " + requestContext.getMediaType()); logger.info("getMethod : " + requestContext.getMethod()); logger.info("getPropertyNames : " + requestContext.getPropertyNames()); logger.info("getStringHeaders : " + requestContext.getStringHeaders()); logger.info("getUri : " + requestContext.getUri()); requestContext.getHeaders().add(CONTENT_TYPE_STRING, TEXT_HTML); }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { logger.info("getAllowedMethods : " + responseContext.getAllowedMethods()); logger.info("getCookies : " + responseContext.getCookies()); logger.info("getDate : " + responseContext.getDate()); logger.info("getEntityStream : " + responseContext.getEntityStream()); logger.info("getEntityTag : " + responseContext.getEntityTag()); logger.info("getHeaders : " + responseContext.getHeaders()); logger.info("getLanguage : " + responseContext.getLanguage()); logger.info("getLastModified : " + responseContext.getLastModified()); logger.info("getLength : " + responseContext.getLength()); logger.info("getLinks : " + responseContext.getLinks()); logger.info("getLocation : " + responseContext.getLocation()); logger.info("getMediaType : " + responseContext.getMediaType()); logger.info("getStatus : " + responseContext.getStatus()); logger.info("getStatusInfo : " + responseContext.getStatusInfo()); responseContext.getHeaders().putSingle(CONTENT_TYPE_STRING, requestContext.getHeaderString(CONTENT_TYPE_STRING)); }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { logger.info("getAllowedMethods : " + responseContext.getAllowedMethods()); logger.info("getCookies : " + responseContext.getCookies()); logger.info("getDate : " + responseContext.getDate()); logger.info("getEntityStream : " + responseContext.getEntityStream()); logger.info("getEntityTag : " + responseContext.getEntityTag()); logger.info("getHeaders : " + responseContext.getHeaders()); logger.info("getLanguage : " + responseContext.getLanguage()); logger.info("getLastModified : " + responseContext.getLastModified()); logger.info("getLength : " + responseContext.getLength()); logger.info("getLinks : " + responseContext.getLinks()); logger.info("getLocation : " + responseContext.getLocation()); logger.info("getMediaType : " + responseContext.getMediaType()); logger.info("getStatus : " + responseContext.getStatus()); logger.info("getStatusInfo : " + responseContext.getStatusInfo()); }
@Override public void filter(ClientRequestContext requestContext) throws IOException { logger.info("getAcceptableLanguages : " + requestContext.getAcceptableLanguages()); logger.info("getClient : " + requestContext.getClient()); logger.info("getConfiguration : " + requestContext.getConfiguration()); logger.info("getCookies : " + requestContext.getCookies()); logger.info("getDate : " + requestContext.getDate()); logger.info("getEntity : " + requestContext.getEntity()); logger.info("getEntityAnnotations : " + requestContext.getEntityAnnotations()); logger.info("getEntityClass : " + requestContext.getEntityClass()); logger.info("getEntityStream : " + requestContext.getEntityStream()); logger.info("getEntityType : " + requestContext.getEntityType()); logger.info("getHeaders : " + requestContext.getHeaders()); logger.info("getLanguage : " + requestContext.getLanguage()); logger.info("getMediaType : " + requestContext.getMediaType()); logger.info("getMethod : " + requestContext.getMethod()); logger.info("getPropertyNames : " + requestContext.getPropertyNames()); logger.info("getStringHeaders : " + requestContext.getStringHeaders()); logger.info("getUri : " + requestContext.getUri()); }
@Override public void filter(ClientRequestContext clientRequestContext) throws IOException { String method = clientRequestContext.getMethod(); URI uri = clientRequestContext.getUri(); MultivaluedMap<String, Object> headers = clientRequestContext.getHeaders(); System.out.printf("Sending %s to: %s\n", method, uri); System.out.printf("Headers:\n"); for(String key : headers.keySet()) { System.out.printf(" %s: %s\n", key, headers.getFirst(key)); } if(clientRequestContext.hasEntity()) { final OutputStream stream = new LoggingStream(clientRequestContext.getEntityStream()); clientRequestContext.setEntityStream(stream); clientRequestContext.setProperty("client.LoggingStream", stream); } }
public void filter(ClientRequestContext requestContext) throws IOException { int size = 0; for (Map.Entry<String, String> entry : RpcContext.getContext().getAttachments().entrySet()) { if (entry.getValue().contains(",") || entry.getValue().contains("=") || entry.getKey().contains(",") || entry.getKey().contains("=")) { throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " must not contain ',' or '=' when using rest protocol"); } // TODO for now we don't consider the differences of encoding and server limit size += entry.getValue().getBytes("UTF-8").length; if (size > MAX_HEADER_SIZE) { throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " is too big"); } StringBuilder attachments = new StringBuilder(); attachments.append(entry.getKey()); attachments.append("="); attachments.append(entry.getValue()); requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString()); } }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { System.out.println("Response = " + requestContext + " " + responseContext); Long start = concurrentRequests.get(requestContext); concurrentRequests.remove(requestContext); long duration = (System.nanoTime() - start); System.out.println("Duration: " + duration); URI uri = requestContext.getUri(); String ipv4 = extractIpAddress(uri); System.out.println("ipv4 = " + ipv4); String serviceName = extractServiceName(uri); System.out.println("serviceName = " + serviceName); String spanName = uri.getPath(); System.out.println("spanName = " + spanName); String traceId = extractTraceId(requestContext).orElse("--no spanid--"); Boolean spanExists = Optional.ofNullable(requestContext.getProperty(SPAN_EXISTED)). map((o) -> (boolean) o). orElse(false); if (spanExists) { this.tracEE.saveChildSpan(traceId, spanName, serviceName, ipv4, duration); } else { this.tracEE.saveParentSpan(spanName, serviceName, ipv4, duration); } }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { // for non-200 response, deal with the custom error messages if (! Response.Status.Family.SUCCESSFUL.equals(responseContext.getStatusInfo().getFamily())) { MetaData metaData = MetaData.builder() .httpRequestMetaData(getRequestMetaData(requestContext)) .httpResponseMetaData(getResponseMetaData(responseContext)) .gotAnswer(true) .targetName(serviceDefinition.getName()) .build(); if (Response.Status.NOT_FOUND.getStatusCode() == responseContext.getStatus()) { throw new ExternalResourceNotFoundException(metaData); } throw new ExternalResourceException(metaData); } }
@Override public void filter(final ClientRequestContext clientRequestContext, final ClientResponseContext clientResponseContext) throws IOException { this.logger.debug("HTTP {} Response from {}: {} {}.", clientRequestContext.getMethod(), clientRequestContext.getUri(), clientResponseContext.getStatus(), clientResponseContext.getStatusInfo().getReasonPhrase()); final String responseEntity = getResponseEntity(clientResponseContext); if (clientResponseContext.getStatus() == 400) { if (responseEntity.contains("invalid_token")) { // Zonky is dumb and throws 400 when it should throw 401 clientResponseContext.setStatus(401); } } responseHeaders = clientResponseContext.getHeaders().entrySet().stream() .filter(e -> e.getValue().size() > 0) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0))); }
@Test public void response() throws IOException { final String key = UUID.randomUUID().toString(); final String key2 = UUID.randomUUID().toString(); final String value = UUID.randomUUID().toString(); final MultivaluedMap<String, String> map = new MultivaluedMapImpl<>(); map.add(key, value); map.addAll(key2, Collections.emptyList()); final ClientRequestContext ctx = Mockito.mock(ClientRequestContext.class); final ClientResponseContext ctx2 = Mockito.mock(ClientResponseContext.class); Mockito.when(ctx2.getHeaders()).thenReturn(map); Mockito.when(ctx2.getStatusInfo()).thenReturn(Mockito.mock(Response.StatusType.class)); final RoboZonkyFilter filter = new RoboZonkyFilter(); filter.filter(ctx, ctx2); SoftAssertions.assertSoftly(softly -> { softly.assertThat(filter.getLastResponseHeader(key)).contains(value); softly.assertThat(filter.getLastResponseHeader(key2)).isEmpty(); }); }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { if (LOG.isTraceEnabled()) { LOG.trace("Response status: {} {}", responseContext.getStatus(), responseContext.getStatusInfo().toString()); LOG.trace("Response headers: {}", responseContext.getHeaders()); InputStream stream = responseContext.getEntityStream(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = stream.read(buffer)) != -1) { result.write(buffer, 0, length); } stream.close(); LOG.trace("Response body: {}", result.toString("UTF-8")); responseContext.setEntityStream(new ByteArrayInputStream(result.toByteArray())); } }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { SpanWrapper spanWrapper = CastUtils .cast(requestContext.getProperty(PROPERTY_NAME), SpanWrapper.class); if (spanWrapper != null && !spanWrapper.isFinished()) { log.finest("Finishing client span"); if (spanDecorators != null) { for (ClientSpanDecorator decorator: spanDecorators) { decorator.decorateResponse(responseContext, spanWrapper.get()); } } spanWrapper.finish(); } }
@Override public void filter(ClientRequestContext requestContext) throws IOException { if (token == null) { throw new IOException("cannot encode with a null token"); } forceJerseyBuffering(requestContext); Consumer<byte[]> dataInterceptor = data -> { if (!requestContext.getHeaders().containsKey(header)) { String xhubHeaderValue = XHub.generateHeaderXHubToken(getEncoder(), getHash(), token, data); requestContext.getHeaders().putSingle(header, xhubHeaderValue); } }; requestContext.setEntityStream(new ByteArrayInterceptingOutputStream(requestContext.getEntityStream(), dataInterceptor)); }
@Override public void filter(ClientRequestContext requestContext) throws IOException { // get the load balanced server info Server server = loadBalancer.chooseServer(null); String host = server.getHost(); int port = server.getPort(); URI uri = requestContext.getUri(); URI lbUri; try { lbUri = new URI(uri.getScheme(), uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IOException(e); } requestContext.setUri(lbUri); }
@Override public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException { StringBuilder debugMsgBuilder = new StringBuilder(); debugMsgBuilder.append("ClientRequest: ").append(request.getMethod()).append("\t"); debugMsgBuilder.append(request.getUri().toASCIIString()).append("\t"); appendObjectHeaders(debugMsgBuilder, "> ", request.getHeaders().entrySet()); appendStringHeaders(debugMsgBuilder, "< ", response.getHeaders().entrySet()); debugMsgBuilder.append(response.getStatusInfo()).append(", length=").append(response.getLength()).append(" "); Long requestStartTime = (Long) request.getProperty(PROPERTY_NANOS); if (requestStartTime != null) { debugMsgBuilder .append((System.nanoTime() - requestStartTime) / MILLISECONDS_PER_NANOSECOND) .append(" ms\t"); } LOG.debug(debugMsgBuilder.toString()); RequestLog.stopTiming(CLIENT_TOTAL_TIMER); }
@Override public void filter(ClientRequestContext requestContext) throws IOException { int size = 0; for (Map.Entry<String, String> entry : RpcContext.getContext().getAttachments().entrySet()) { if (entry.getValue().contains(",") || entry.getValue().contains("=") || entry.getKey().contains(",") || entry.getKey().contains("=")) { throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " must not contain ',' or '=' when using rest protocol"); } // TODO for now we don't consider the differences of encoding and // server limit size += entry.getValue().getBytes("UTF-8").length; if (size > MAX_HEADER_SIZE) { throw new IllegalArgumentException( "The attachments of " + RpcContext.class.getSimpleName() + " is too big"); } StringBuilder attachments = new StringBuilder(); attachments.append(entry.getKey()); attachments.append("="); String encode = URLEncoder.encode(entry.getValue(), "UTF-8"); attachments.append(encode); requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString()); } }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { if (responseContext.getStatus() != Response.Status.OK.getStatusCode() && responseContext.hasEntity()) { try { final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); final Error error = (Error) unmarshaller.unmarshal(responseContext.getEntityStream()); final Response.ResponseBuilder builder = Response.status(responseContext.getStatusInfo()); builder.entity(error); // copy response headers for (Map.Entry<String, List<String>> header : responseContext.getHeaders().entrySet()) { builder.header(header.getKey(), header.getValue()); } throw new LinkedInException(error, builder.build()); } catch (JAXBException e) { // log and ignore LOG.warn("Unable to parse LinkedIn error: " + e.getMessage(), e); } } }
@Override public void filter(ClientRequestContext clientRequestContext) throws IOException { final HttpClientRequest httpClientRequest = new HttpClientRequest() { @Override public void addHeader(String s, String s1) { clientRequestContext.getHeaders().add(s, s1); } @Override public URI getUri() { return clientRequestContext.getUri(); } @Override public String getHttpMethod() { return clientRequestContext.getMethod(); } }; requestInterceptor.handle(new HttpClientRequestAdapter(httpClientRequest, spanNameProvider)); }
private boolean isRedirectWithinLimits(ClientRequestContext requestContext, URI nextLocation) { final Set<URI> visitedLocations = getVisitedLocations(requestContext); if (visitedLocations.contains(nextLocation)) { log.warn("Detected redirect cycle: {} -> {}", visitedLocations, nextLocation); return false; } if (visitedLocations.size() > maxRedirectHops) { log.warn("Reached max hops ({}) following redirects: {}", maxRedirectHops, visitedLocations); return false; } return true; }
private WebTarget getWebTarget() { if (client == null) { client = ClientBuilder.newClient(); client.register(JacksonJsonProvider.class); // register the basic authentication filter if authentication information is provided if (authenticationToken != null) { client.register(new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().add("Authorization", "Basic " + authenticationToken); } }); } } WebTarget target = client.target(targetUrl); return target; }
public WordPressClientFactory withCredentials(String username, String password) { this.clientRequestFilter = new ClientRequestFilter() { private final String charset = StandardCharsets.UTF_8.name(); @Override public void filter(ClientRequestContext requestContext) throws IOException { String token = String.format("%s:%s", username, password); String basicAuthHeader = null; try { basicAuthHeader = "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes(charset)); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException("Cannot encode with " + charset, ex); } MultivaluedMap<String, Object> headers = requestContext.getHeaders(); headers.add("Authorization", basicAuthHeader); logger.trace("Added BasicAuth filter with username {}", username); } }; return this; }
/** * Intercepts the client response flow and extract response information * to be published to the DAS server for tracing. */ @Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { long time = new Date().getTime(); TraceEvent traceEvent = (TraceEvent) requestContext.getProperty(TRACE_EVENT_ATTRIBUTE); if (traceEvent != null) { TraceEvent endTraceEvent = new TraceEvent( TracingConstants.CLIENT_TRACE_END, traceEvent.getTraceId(), traceEvent.getOriginId(), time ); endTraceEvent.setStatusCode(responseContext.getStatus()); TracingUtil.pushToDAS(endTraceEvent, dasUrl); } }
/** * Check parameters on request Context * @param requestContext */ private void checkParams(ClientRequestContext requestContext){ if (key==null) { Object keyObject = requestContext.getProperty(JWS_FILTER_KEY); if (keyObject == null) { requestContext.abortWith( Response.status(Response.Status.BAD_REQUEST).entity("Error " + JWS_FILTER_KEY + " param is required") .build() ); }else if (keyObject instanceof RSAPrivateKey) { key = (RSAPrivateKey)keyObject; } } }
@Override public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) { try { // For non-200 response, log the custom error message. if (responseContext.getStatus() != Response.Status.OK.getStatusCode()) { if (responseContext.hasEntity()) { String error = CharStreams.toString( new InputStreamReader(responseContext.getEntityStream(), Charsets.UTF_8)); LOG.severe(error); System.err.println(error); } } } catch (Exception e) { // Silently pass. We don't want anything to fail because of this filter. LOG.warning("Error while checking response code: " + e.getMessage()); } }
/** * {@inheritDoc} */ @Override public void filter(final ClientRequestContext context) throws IOException { final long id = _id.incrementAndGet(); context.setProperty(LOGGING_ID_PROPERTY, id); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders()); if (printEntity && context.hasEntity() && isSupportPrintType(context.getMediaType())) { final OutputStream stream = new LoggingStream(b, context.getEntityStream()); context.setEntityStream(stream); context.setProperty(ENTITY_LOGGER_PROPERTY, stream); // not calling log(b) here - it will be called by the interceptor } else { log(b); } }
private void logRequest(ClientRequestContext requestContext) throws IOException { Object requestBody = requestContext.getEntity(); if (log.isTraceEnabled()) { StringBuffer sbuf = new StringBuffer("\nHeaders:"); sbuf.append("\n--- BEGIN ---"); MultivaluedMap<String,String> headers = requestContext.getStringHeaders(); for (String key : headers.keySet()) { sbuf.append("\n").append(key).append("=").append(headers.get(key)); } // end for key sbuf.append("\n--- END ---"); log.trace(sbuf.toString()); sbuf = null; } // end if if (MediaType.APPLICATION_JSON.equals(requestContext.getHeaderString(HttpHeaders.CONTENT_TYPE))) { log.debug("\n["+requestContext.getMethod()+"] : "+requestContext.getUri().toString()+"\n"+JiveSDKUtils.getJson(requestBody)); } else { log.debug("\n["+requestContext.getMethod()+"] : "+requestContext.getUri().toString()+"\n"+requestBody); } // end if }
@Override public void filter(final ClientRequestContext context) throws IOException { final long id = aid.incrementAndGet(); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders()); if (printEntity && context.hasEntity()) { final OutputStream stream = new LoggingStream(b, context.getEntityStream()); context.setEntityStream(stream); context.setProperty(ENTITY_LOGGER_PROPERTY, stream); // not calling log(b) here - it will be called by the interceptor } else { log(b); } }
@Override public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { int status = responseContext.getStatus(); switch (status) { case 200: case 201: case 204: return; case 304: throw new NotModifiedException(getBodyAsMessage(responseContext)); case 400: throw new BadRequestException(getBodyAsMessage(responseContext)); case 401: throw new UnauthorizedException(getBodyAsMessage(responseContext)); case 404: throw new NotFoundException(getBodyAsMessage(responseContext)); case 406: throw new NotAcceptableException(getBodyAsMessage(responseContext)); case 409: throw new ConflictException(getBodyAsMessage(responseContext)); case 500: throw new InternalServerErrorException(getBodyAsMessage(responseContext)); default: throw new DockerException(getBodyAsMessage(responseContext), status); } }
public void filter(ClientRequestContext requestContext) throws IOException { // Wrap entity to store property filters SpearalPropertyFilterBuilder clientPropertyFilterBuilder = (SpearalPropertyFilterBuilder)requestContext.getProperty(SpearalJaxrs.PROPERTY_FILTER_CLIENT); if (clientPropertyFilterBuilder != null) requestContext.setEntity(new SpearalEntity(requestContext.getEntity(), clientPropertyFilterBuilder)); // Transmit server property filters as http header SpearalPropertyFilterBuilder serverPropertyFilterBuilder = (SpearalPropertyFilterBuilder)requestContext.getProperty(SpearalJaxrs.PROPERTY_FILTER_SERVER); if (serverPropertyFilterBuilder == null) return; SpearalFactory factory = SpearalJaxrs.locateFactory(configuration, providers); List<Object> serverPropertyFilterHeaders = new ArrayList<Object>(serverPropertyFilterBuilder.toHeaders(factory.getContext())); requestContext.getHeaders().put(Spearal.PROPERTY_FILTER_HEADER, serverPropertyFilterHeaders); }
@Override public void filter( final ClientRequestContext requestContext ) throws IOException { final String accessToken = _keycloak.getAccessTokenString(); if ( null != accessToken ) { requestContext.getHeaders().add( HttpHeaders.AUTHORIZATION, AUTH_HEADER_PREFIX + accessToken ); } }
@Override public void filter( final ClientRequestContext requestContext ) throws IOException { final String pair = _username + ":" + _password; final String header = "Basic " + Base64.getEncoder().encodeToString( pair.getBytes() ); requestContext.getHeaders().add( HttpHeaders.AUTHORIZATION, header ); }