@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { long id = ++_id; StringBuilder requestString = new StringBuilder(); logRequest(id, request, requestString); LoggingBean loggingBean = new LoggingBean(); loggingBean.setCommandName(request.getMethod() + ":" + request.getURI()); loggingBean.setArgs(new String[] { request.getURI().getPath(), request.getURI().getQuery() }); ClientResponse response = getNext().handle(request); loggingBean.setResult(response.toString()); StringBuilder responseString = logResponse(id, response); LoggingBean detailsLoggingBean = new LoggingBean(); detailsLoggingBean.setArgs(new String[] { noPrifix(requestString).toString() }); detailsLoggingBean.setResult(noPrifix(responseString).toString()); loggingBean.getSubLogs().add(detailsLoggingBean); TestBaseProvider.instance().get().getLog().add(loggingBean); return response; }
private void printRequestHeaders(StringBuilder b, long id, MultivaluedMap<String, Object> headers) { for (Map.Entry<String, List<Object>> e : headers.entrySet()) { List<Object> val = e.getValue(); String header = e.getKey(); if (val.size() == 1) { prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ") .append(ClientRequest.getHeaderValue(val.get(0))).append("\n"); } else { StringBuilder sb = new StringBuilder(); boolean add = false; for (Object o : val) { if (add) { sb.append(','); } add = true; sb.append(ClientRequest.getHeaderValue(o)); } prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ").append(sb.toString()).append("\n"); } } }
@Override public ClientResponse handle(ClientRequest cr) throws ClientHandlerException { URIBuilder uriBuilder = new URIBuilder(cr.getURI()); String path = uriBuilder.getPath(); uriBuilder.setPath(converter.convertCommandPath(path)); try { cr.setURI(uriBuilder.build()); ClientResponse response = getNext().handle(cr); String newEntity = converter.convertResponse(path, response.getEntity(String.class)); response.setEntityInputStream(new ByteArrayInputStream(newEntity.getBytes())); return response; } catch (Exception ex) { throw new ClientHandlerException(ex); } }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { String uuid = UUID.randomUUID().toString(); if (LOGGER.isDebugEnabled()) { logRequest(uuid, request); } ClientResponse response = getNext().handle(request); if (LOGGER.isDebugEnabled()) { logResponse(uuid, response); } return response; }
private void logRequest(String uuid, ClientRequest request) { final StringBuffer sb = new StringBuffer(); sb.append(uuid + "\n" + request.getMethod() + " " + request.getURI() + "\n"); request.getHeaders().forEach( (k, v) -> { String value = v.stream() .map(e -> (e == null ? "" : e.toString())) .collect(Collectors.joining(";")); sb.append(k + ": " + value + "\n"); }); Optional.ofNullable(request.getEntity()).ifPresent( e -> sb.append("Body: " + e)); LOGGER.debug(sb.toString()); }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { String userAgent = ""; try { Properties prop = ResourceUtil.loadProperiesOnResourceFolder(Constant.RAPID_API_RESOURCE); userAgent = prop.getProperty(Constant.RAPID_SDK_USER_AGENT_PARAM); if (StringUtils.isBlank(userAgent)) { throw new Exception("Resource file " + Constant.RAPID_API_RESOURCE + " is invalid."); } } catch (Exception e) { LOGGER.error("User Agent could not be loaded", e); } request.getHeaders().putSingle(HttpHeaders.USER_AGENT, userAgent); if (this.apiVersion != null) { request.getHeaders().putSingle("X-EWAY-APIVERSION", this.apiVersion); } return getNext().handle(request); }
/** * Get the serialized representation of the request entity. This is used when generating the client * signature, because this is the representation that the server will receive and use when it generates * the server-side signature to compare to the client-side signature. * * @see com.sun.jersey.client.urlconnection.URLConnectionClientHandler */ private byte[] getSerializedEntity(ClientRequest request) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // By using the RequestWriter parent class, we match the behavior of entity writing from // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler. writeRequestEntity(request, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) throws IOException { } public OutputStream onGetOutputStream() throws IOException { return outputStream; } }); } catch (IOException e) { throw new ClientHandlerException("Unable to serialize request entity", e); } return outputStream.toByteArray(); }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { MultivaluedMap headers = request.getHeaders(); try { if(cloudSpace != null) { headers.add("x-tmrk-cloudspace", cloudSpace); } String signature = sign(request, headers); headers.add("x-tmrk-authorization", new StringBuilder().append("CloudApi AccessKey=").append(getAccessKey()).append(" SignatureType=").append("HmacSHA256").append(" Signature=").append(signature).toString()); } catch (Exception ex) { throw new ClientHandlerException("Error signing request headers", ex); } return getNext().handle(request); }
private static String getCanonicalizedResource(ClientRequest request) { Map<String, Object> queryMap = new TreeMap(); String query = request.getURI().getQuery(); if ((query != null) && (query.length() > 0)) { String[] parts = query.split("&"); for (String part : parts) { String[] nameValue = part.split("="); if (nameValue.length == 2) { queryMap.put(nameValue[0].toLowerCase(), nameValue[1]); } } } StringBuilder builder = new StringBuilder(); builder.append(request.getURI().getPath().toLowerCase()).append('\n'); for (Map.Entry entry : queryMap.entrySet()) { builder.append((String) entry.getKey()).append(':').append((String) entry.getValue()).append('\n'); } return builder.toString(); }
@Before public void setup() { dummy = context.mock(ClientHandler.class); authFilter = new BasicAuthFilter("admin", "lamepass"); ReflectionTestUtils.setField(authFilter, "next", dummy); clientRequest = context.mock(ClientRequest.class); headers = new MultivaluedMapImpl(); context.checking(new Expectations() { { allowing(clientRequest).getHeaders(); will(returnValue(headers)); allowing(dummy).handle(with(aNonNull(ClientRequest.class))); will(returnValue(null)); } }); }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { addTokenToRequest(request); ClientResponse response = getNext().handle(request); // Handle a redirect if (response.getClientResponseStatus() == ClientResponse.Status.FOUND) { if (response.getHeaders().containsKey(HttpHeaders.LOCATION)) { String location = response.getHeaders().getFirst(HttpHeaders.LOCATION); final ClientRequest newRequest = ClientRequest.create().build(URI.create(location), request.getMethod()); // Handle the token from the existing response, add to this new request checkResponseForToken(response); addTokenToRequest(newRequest); // Call handler to perform redirect to new page response = handle(newRequest); } } checkResponseForToken(response); return response; }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { ClientResponse response = getNext().handle(request); int status = response.getStatus(); if (status >= 400 && status < 600) { if (isSupportedType(response.getType())) { ServiceErrorRestRep serviceError; try { serviceError = response.getEntity(ServiceErrorRestRep.class); } catch (Exception e) { // Cause to fall-through to default exception log.error("Error parsing error message", e); serviceError = null; } if (serviceError != null) { logAndThrow(new ServiceErrorException(status, serviceError)); } } // Fallback for unknown entity types String content = response.getEntity(String.class); logAndThrow(new ViPRHttpException(status, content)); } return response; }
@Override public ClientResponse handle(ClientRequest clientRequest) { Throwable cause = null; for (int retryCount = 1; retryCount <= maxRetries; retryCount++) { try { ClientResponse response = getNext().handle(clientRequest); return response; } catch (ServiceErrorException e) { if (!e.isRetryable()) { throw e; } cause = e; } log.info("Request failed {}, retrying (count: {})", clientRequest.getURI().toString(), retryCount); try { Thread.sleep(retryInterval); } catch (InterruptedException exception) { // Ignore this } } throw new ViPRException("Retry limit exceeded", cause); }
private void printRequestHeaders(StringBuilder b, long id, MultivaluedMap<String, Object> headers) { for (Map.Entry<String, List<Object>> e : headers.entrySet()) { List<Object> val = e.getValue(); String header = e.getKey(); if(val.size() == 1) { prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ").append(ClientRequest.getHeaderValue(val.get(0))).append("\n"); } else { StringBuilder sb = new StringBuilder(); boolean add = false; for(Object o : val) { if(add) sb.append(','); add = true; sb.append(ClientRequest.getHeaderValue(o)); } prefixId(b, id).append(REQUEST_PREFIX).append(header).append(": ").append(sb.toString()).append("\n"); } } }
public SourceDescriptionState readSourceDescription(SourceReference sourceReference, StateTransitionOption... options) { Link link = sourceReference.getLink(Rel.DESCRIPTION); link = link == null ? sourceReference.getLink(Rel.SELF) : link; org.gedcomx.common.URI href; if (link != null) { href = link.getHref(); } else { href = sourceReference.getDescriptionRef(); } if (href == null) { throw new GedcomxApplicationException("Source description cannot be read: missing link."); } ClientRequest request = createAuthenticatedGedcomxRequest().build(href.toURI(), HttpMethod.GET); return this.stateFactory.newSourceDescriptionState(request, invoke(request, options), this.accessToken); }
private void logRequest(long id, ClientRequest request, StringBuilder b) { printRequestLine(b, id, request); printRequestHeaders(b, id, request.getHeaders()); if (request.getEntity() != null) { prefixId(b, id).append(REQUEST_PREFIX).append(request.getEntity()); request.setAdapter(new Adapter(request.getAdapter(), b)); } log(b.toString()); }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { ClientResponse response = getNext().handle(request); clientRequest = request; clientResponse = response; return response; }
protected void finishClientSpan(ClientRequest requestCtx) { Span span = this.clientSpans.get(requestCtx); if (span != null) { this.clientSpans.remove(requestCtx); span.finish(); } }
@Override public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException { final MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); List<Object> hcookies = headers.get(COOKIE_HEADER); if (hcookies == null) { hcookies = new ArrayList<>(); } hcookies.addAll(cookies); headers.put(COOKIE_HEADER, hcookies); return getNext().handle(clientRequest); }
@Override public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException { ClientResponse response = getNext().handle(cr); if (response.getStatus() < 300) { return response; // normal valid response } MultivaluedMap<String, String> headers = response.getHeaders(); String exType = headers.getFirst(EXCEPTION_TYPE); String exMsg = headers.getFirst(EXCEPTION_MESSAGE); if (exMsg == null) { exMsg = headers.getFirst(EXCEPTION_POINT); } UniformInterfaceException uiex; if (response.getStatus() == 404) { uiex = new UniformInterfaceException404NotFound(response, true); } else if (response.getStatus() == 204) { uiex = new UniformInterfaceException204NoContent(response, true); } else { uiex = new UniformInterfaceException(response, true); } if (exType == null) { throw uiex; // standard UniformInterfaceException as we have nothing to add } RuntimeException exception; try { Class<? extends RuntimeException> cls = ClassUtils.loadClass(exType).asSubclass(RuntimeException.class); exception = cls.getConstructor(String.class).newInstance("Server threw exception: " + StringUtils.defaultString(exMsg)); } catch (Exception ex) { // unable to create transparently, so use standard exception exception = new OpenGammaRuntimeException("Server threw exception: " + exType + ": " + StringUtils.defaultString(exMsg)); } exception.initCause(uiex); throw exception; // transparently throw exception as seen on the server }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { // Modify the request to include security credentials if appropriate if (shouldEncode(request)) { requestEncoder.encode(request); } // Following the ClientFilter protocol, pass the request to the next filter in the chain return getNext().handle(request); }
public void encode(ClientRequest request) { String timestamp = TimeUtils.getCurrentTimestamp(); addApiKey(request); addTimestamp(request, timestamp); addSignature(request, timestamp); addVersion(request, Version.V1); }
private void addApiKey(ClientRequest request) { URI uriWithApiKey = UriBuilder.fromUri(request.getURI()) .queryParam(this.requestConfiguration.getApiKeyQueryParamName(), apiKey) .build(); request.setURI(uriWithApiKey); }
private void appendRequestDetails(@Nonnull ClientRequest request, @Nonnull DebugData restCall) { try { restCall.set("Type", "RestCall"); restCall.set("Url", request.getURI().toASCIIString()); restCall.set("Method", request.getMethod()); restCall.set("Async", async); restCall.set("RequestHeaders", getRequestHeaders(request)); if(request.getEntity() != null){ restCall.set("Payload", request.getEntity()); } } catch (Exception ignored) { } }
@Before public void setUp() throws Exception { next = mock(ClientHandler.class); restResponse = mock(ClientResponse.class); restRequest = mock(ClientRequest.class); filter = new DebugJerseyFilter(); filter.setAsync(isAsync); filter.setDisabled(false); DebugContext.init(null); ReflectionTestUtils.setField(filter, "next", next); }
private String sign(ClientRequest request, MultivaluedMap<String, Object> headers) throws IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { StringBuilder stringToSign = new StringBuilder().append(getVerb(request)).append(getContentType(headers)).append(getDate(headers)).append(getCanonicalizedHeaders(headers)).append(getCanonicalizedResource(request)); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(getSecretKey().getBytes("UTF-8"), "HmacSHA256")); byte[] digest = mac.doFinal(stringToSign.toString().getBytes("UTF-8")); return new String(Base64.encode(digest)).trim(); }
/** * {@inheritDoc} */ @Override public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException { if (!cr.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { cr.getHeaders().add(HttpHeaders.AUTHORIZATION, authentication); } return getNext().handle(cr); }
@Override public ClientResponse handle(ClientRequest request) throws ClientHandlerException { ClientResponse response = getNext().handle(request); int status = response.getStatus(); if (supportsPortalValidation(request) && status == 400) { List<ValidationError> errorsList = ApiListUtils.getEntityList(config, new GenericType<List<ValidationError>>() { }, response); ValidationException exception = new ValidationException(response.getStatus(), errorsList); LOG.error(exception.getMessage()); throw exception; } return response; }
private void logRequest(long id, ClientRequest request) { StringBuilder b = new StringBuilder(); printRequestLine(b, id, request); printRequestHeaders(b, id, request.getHeaders()); if (request.getEntity() != null) { request.setAdapter(new Adapter(request.getAdapter(), b)); } else { log(b); } }
public RecordState readRecord(SourceDescription sourceDescription, StateTransitionOption... options) { Link link = sourceDescription.getLink(Rel.RECORD); if (link == null || link.getHref() == null) { return null; } ClientRequest request = createAuthenticatedGedcomxRequest().build(link.getHref().toURI(), HttpMethod.GET); return this.stateFactory.newRecordState(request, invoke(request, options), this.accessToken); }
public RelationshipsState addRelationships(List<Relationship> relationships, StateTransitionOption... options) { Link link = getLink(Rel.RELATIONSHIPS); if (link == null || link.getHref() == null) { throw new GedcomxApplicationException(String.format("Collection at %s doesn't support adding relationships.", getUri())); } Gedcomx entity = new Gedcomx(); entity.setRelationships(relationships); ClientRequest request = createAuthenticatedGedcomxRequest().entity(entity).build(link.getHref().toURI(), HttpMethod.POST); return this.stateFactory.newRelationshipsState(request, invoke(request, options), this.accessToken); }
public DescendancyResultsState readDescendancy(StateTransitionOption... options) { Link link = getLink(Rel.DESCENDANCY); if (link == null || link.getHref() == null) { return null; } ClientRequest request = createAuthenticatedGedcomxRequest().build(link.getHref().toURI(), HttpMethod.GET); return this.stateFactory.newDescendancyResultsState(request, invoke(request, options), this.accessToken); }
public SourceDescriptionsState readSourceDescriptions(StateTransitionOption... options) { Link link = getLink(Rel.SOURCE_DESCRIPTIONS); if (link == null || link.getHref() == null) { return null; } ClientRequest request = createAuthenticatedGedcomxRequest().build(link.getHref().toURI(), HttpMethod.GET); return this.stateFactory.newSourceDescriptionsState(request, invoke(request, options), this.accessToken); }
public ChildAndParentsRelationshipState deleteSourceReference(SourceReference reference, StateTransitionOption... options) { Link link = reference.getLink(Rel.SOURCE_REFERENCE); link = link == null ? reference.getLink(Rel.SELF) : link; if (link == null || link.getHref() == null) { throw new GedcomxApplicationException("Source reference cannot be deleted: missing link."); } ClientRequest request = RequestUtil.applyFamilySearchConneg(createAuthenticatedRequest()).build(link.getHref().toURI(), HttpMethod.DELETE); return ((FamilyTreeStateFactory)this.stateFactory).newChildAndParentsRelationshipState(request, invoke(request, options), this.accessToken); }
public PersonState deleteEvidenceReference(EvidenceReference reference, StateTransitionOption... options) { Link link = reference.getLink(Rel.EVIDENCE_REFERENCE); link = link == null ? reference.getLink(Rel.SELF) : link; if (link == null || link.getHref() == null) { throw new GedcomxApplicationException("Evidence reference cannot be deleted: missing link."); } ClientRequest request = createAuthenticatedGedcomxRequest().build(link.getHref().toURI(), HttpMethod.DELETE); return this.stateFactory.newPersonState(request, invoke(request, options), this.accessToken); }
public SourceDescriptionState addSourceDescription(SourceDescription source, StateTransitionOption... options) { Link link = getLink(Rel.SOURCE_DESCRIPTIONS); if (link == null || link.getHref() == null) { throw new GedcomxApplicationException(String.format("Collection at %s doesn't support adding source descriptions.", getUri())); } Gedcomx entity = new Gedcomx(); entity.addSourceDescription(source); ClientRequest request = createAuthenticatedGedcomxRequest().entity(entity).build(link.getHref().toURI(), HttpMethod.POST); return this.stateFactory.newSourceDescriptionState(request, invoke(request, options), this.accessToken); }
public PersonState updateNotes(Person person, StateTransitionOption... options) { URI target = getSelfUri(); Link conclusionsLink = getLink(Rel.NOTES); if (conclusionsLink != null && conclusionsLink.getHref() != null) { target = conclusionsLink.getHref().toURI(); } Gedcomx gx = new Gedcomx(); gx.setPersons(Arrays.asList(person)); ClientRequest request = createAuthenticatedGedcomxRequest().entity(gx).build(target, HttpMethod.POST); return this.stateFactory.newPersonState(request, invoke(request, options), this.accessToken); }
public RelationshipState readRelationship(Relationship relationship, StateTransitionOption... options) { Link link = relationship.getLink(Rel.RELATIONSHIP); link = link == null ? relationship.getLink(Rel.SELF) : link; if (link == null || link.getHref() == null) { return null; } ClientRequest request = createAuthenticatedGedcomxRequest().build(link.getHref().toURI(), HttpMethod.GET); return this.stateFactory.newRelationshipState(request, invoke(request, options), this.accessToken); }
public PersonState readRelative(Relationship relationship, StateTransitionOption... options) { ResourceReference reference = null; if (refersToMe(relationship.getPerson1())) { reference = relationship.getPerson2(); } else if (refersToMe(relationship.getPerson2())) { reference = relationship.getPerson1(); } if (reference == null || reference.getResource() == null) { return null; } ClientRequest request = createAuthenticatedGedcomxRequest().build(reference.getResource().toURI(), HttpMethod.GET); return this.stateFactory.newPersonState(request, invoke(request, options), this.accessToken); }
@Override public TempleCardPrintSetState get(StateTransitionOption... options) { ClientRequest.Builder builder = createAuthenticatedRequest(); builder = builder.accept("application/pdf"); ClientRequest request = builder.build(getSelfUri(), HttpMethod.GET); ClientResponse response = invoke(request, options); return (TempleCardPrintSetState) clone(request, response); }