javax.ws.rs.core.MultivaluedMap Java Examples
The following examples show how to use
javax.ws.rs.core.MultivaluedMap.
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: VirtualInstanceCollectionMessageBodyWriter.java From eplmp with Eclipse Public License 1.0 | 6 votes |
@Override public void writeTo(VirtualInstanceCollection virtualInstanceCollection, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws UnsupportedEncodingException { String charSet = "UTF-8"; JsonGenerator jg = Json.createGenerator(new OutputStreamWriter(entityStream, charSet)); jg.writeStartArray(); Matrix4d gM = new Matrix4d(); gM.setIdentity(); PartLink virtualRootPartLink = getVirtualRootPartLink(virtualInstanceCollection); List<PartLink> path = new ArrayList<>(); path.add(virtualRootPartLink); InstanceBodyWriterTools.generateInstanceStreamWithGlobalMatrix(productService, path, gM, virtualInstanceCollection, new ArrayList<>(), jg); jg.writeEnd(); jg.flush(); }
Example #2
Source File: AbstractTokenService.java From cxf with Apache License 2.0 | 6 votes |
protected Client getClientFromTLSCertificates(SecurityContext sc, TLSSessionInfo tlsSessionInfo, MultivaluedMap<String, String> params) { Client client = null; if (OAuthUtils.isMutualTls(sc, tlsSessionInfo)) { X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo); String subjectDn = OAuthUtils.getSubjectDnFromTLSCertificates(cert); if (!StringUtils.isEmpty(subjectDn)) { client = getClient(subjectDn, params); validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS); // The certificates must be registered with the client and match TLS certificates // in case of the binding where Client's clientId is a subject distinguished name compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates()); OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert); } } return client; }
Example #3
Source File: BinaryDataProvider.java From cxf with Apache License 2.0 | 6 votes |
protected void copyInputToOutput(InputStream is, OutputStream os, Annotation[] anns, MultivaluedMap<String, Object> outHeaders) throws IOException { if (isRangeSupported()) { Message inMessage = PhaseInterceptorChain.getCurrentMessage().getExchange().getInMessage(); handleRangeRequest(is, os, new HttpHeadersImpl(inMessage), outHeaders); } else { boolean nioWrite = AnnotationUtils.getAnnotation(anns, UseNio.class) != null; if (nioWrite) { ContinuationProvider provider = getContinuationProvider(); if (provider != null) { copyUsingNio(is, os, provider.getContinuation()); } return; } if (closeResponseInputStream) { IOUtils.copyAndCloseInput(is, os, bufferSize); } else { IOUtils.copy(is, os, bufferSize); } } }
Example #4
Source File: ResponseImplTest.java From cxf with Apache License 2.0 | 6 votes |
private Source readResponseSource(ResponseImpl r) { String content = "<Response " + " xmlns=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\"" + " xmlns:ns2=\"urn:oasis:names:tc:xacml:2.0:policy:schema:os\">" + "<Result><Decision>Permit</Decision><Status><StatusCode" + " Value=\"urn:oasis:names:tc:xacml:1.0:status:ok\"/></Status></Result></Response>"; MultivaluedMap<String, Object> headers = new MetadataMap<>(); headers.putSingle("Content-Type", "text/xml"); r.addMetadata(headers); r.setEntity(new ByteArrayInputStream(content.getBytes()), null); r.setOutMessage(createMessage()); r.bufferEntity(); return r.readEntity(Source.class); }
Example #5
Source File: SchemaRegistryResource.java From registry with Apache License 2.0 | 6 votes |
private SchemaFieldQuery buildSchemaFieldQuery(MultivaluedMap<String, String> queryParameters) { SchemaFieldQuery.Builder builder = new SchemaFieldQuery.Builder(); for (Map.Entry<String, List<String>> entry : queryParameters.entrySet()) { List<String> entryValue = entry.getValue(); String value = entryValue != null && !entryValue.isEmpty() ? entryValue.get(0) : null; if (value != null) { if (SchemaFieldInfo.FIELD_NAMESPACE.equals(entry.getKey())) { builder.namespace(value); } else if (SchemaFieldInfo.NAME.equals(entry.getKey())) { builder.name(value); } else if (SchemaFieldInfo.TYPE.equals(entry.getKey())) { builder.type(value); } } } return builder.build(); }
Example #6
Source File: DownloadFileResponseFilter.java From che with Eclipse Public License 2.0 | 6 votes |
/** * Check if we need to apply a filter * * @param request * @return */ protected String getFileName( Request request, MediaType mediaType, UriInfo uriInfo, int responseStatus) { // manage only GET requests if (!HttpMethod.GET.equals(request.getMethod())) { return null; } // manage only OK code if (Response.Status.OK.getStatusCode() != responseStatus) { return null; } // Only handle JSON content if (!MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { return null; } // check if parameter filename is given MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); return queryParameters.getFirst(QUERY_DOWNLOAD_PARAMETER); }
Example #7
Source File: LogoutService.java From cxf-fediz with Apache License 2.0 | 6 votes |
private static URI getClientLogoutUri(final Client client, final MultivaluedMap<String, String> params) { String logoutUriProp = client.getProperties().get(CLIENT_LOGOUT_URIS); // logoutUriProp is guaranteed to be not null at this point String[] uris = logoutUriProp.split(" "); String clientLogoutUriParam = params.getFirst(CLIENT_LOGOUT_URI); final String uriStr; if (uris.length > 1) { if (clientLogoutUriParam == null || !new HashSet<>(Arrays.asList(uris)).contains(clientLogoutUriParam)) { throw new BadRequestException(); } uriStr = clientLogoutUriParam; } else { if (clientLogoutUriParam != null && !uris[0].equals(clientLogoutUriParam)) { throw new BadRequestException(); } uriStr = uris[0]; } UriBuilder ub = UriBuilder.fromUri(uriStr); String state = params.getFirst(OAuthConstants.STATE); if (state != null) { ub.queryParam(OAuthConstants.STATE, state); } return ub.build().normalize(); }
Example #8
Source File: JAXRSUtilsTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testFormParametersBeanWithMap() throws Exception { Class<?>[] argType = {Customer.CustomerBean.class}; Method m = Customer.class.getMethod("testFormBean", argType); Message messageImpl = createMessage(); messageImpl.put(Message.REQUEST_URI, "/bar"); MultivaluedMap<String, String> headers = new MetadataMap<>(); headers.putSingle("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); messageImpl.put(Message.PROTOCOL_HEADERS, headers); String body = "g.b=1&g.b=2"; messageImpl.setContent(InputStream.class, new ByteArrayInputStream(body.getBytes())); List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m, new ClassResourceInfo(Customer.class)), null, messageImpl); assertEquals("Bean should be created", 1, params.size()); Customer.CustomerBean cb = (Customer.CustomerBean)params.get(0); assertNotNull(cb); assertNotNull(cb.getG()); List<String> values = cb.getG().get("b"); assertEquals(2, values.size()); assertEquals("1", values.get(0)); assertEquals("2", values.get(1)); }
Example #9
Source File: SchemaRegistryResource.java From registry with Apache License 2.0 | 6 votes |
@GET @Path("/search/schemas") @ApiOperation(value = "Search for schemas containing the given name and description", notes = "Search the schemas for given name and description, return a list of schemas that contain the field.", response = SchemaMetadataInfo.class, responseContainer = "List", tags = OPERATION_GROUP_SCHEMA) @Timed @UnitOfWork public Response findSchemas(@Context UriInfo uriInfo, @Context SecurityContext securityContext) { MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); try { Collection<SchemaMetadataInfo> schemaMetadataInfos = authorizationAgent .authorizeFindSchemas(AuthorizationUtils.getUserAndGroups(securityContext), findSchemaMetadataInfos(queryParameters)); return WSUtils.respondEntities(schemaMetadataInfos, Response.Status.OK); } catch (Exception ex) { LOG.error("Encountered error while finding schemas for given fields [{}]", queryParameters, ex); return WSUtils.respond(Response.Status.INTERNAL_SERVER_ERROR, CatalogResponse.ResponseMessage.EXCEPTION, ex.getMessage()); } }
Example #10
Source File: PropertyFilteringMessageBodyWriter.java From jackson-jaxrs-propertyfiltering with Apache License 2.0 | 6 votes |
@Override public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException { PropertyFiltering annotation = findPropertyFiltering(annotations); PropertyFilter propertyFilter = PropertyFilterBuilder.newBuilder(uriInfo).forAnnotation(annotation); if (!propertyFilter.hasFilters()) { write(o, type, genericType, annotations, mediaType, httpHeaders, os); return; } Timer timer = getTimer(); Timer.Context context = timer.time(); try { ObjectMapper mapper = getJsonProvider().locateMapper(type, mediaType); ObjectWriter writer = JsonEndpointConfig.forWriting(mapper.writer(), annotations, null).getWriter(); writeValue(writer, propertyFilter, o, os); } finally { context.stop(); } }
Example #11
Source File: BasedModelProvider.java From Processor with Apache License 2.0 | 6 votes |
@Override public Model readFrom(Class<Model> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { if (log.isTraceEnabled()) log.trace("Reading Model with HTTP headers: {} MediaType: {}", httpHeaders, mediaType); Model model = ModelFactory.createDefaultModel(); MediaType formatType = new MediaType(mediaType.getType(), mediaType.getSubtype()); // discard charset param Lang lang = RDFLanguages.contentTypeToLang(formatType.toString()); if (lang == null) { if (log.isErrorEnabled()) log.error("MediaType '{}' not supported by Jena", formatType); throw new NoReaderForLangException("MediaType not supported: " + formatType); } if (log.isDebugEnabled()) log.debug("RDF language used to read Model: {}", lang); return read(model, entityStream, lang, getUriInfo().getBaseUri().toString()); }
Example #12
Source File: RegisterAuthenticatorTest.java From keycloak-webauthn-authenticator with Apache License 2.0 | 6 votes |
@Test public void test_action_webauthn4j_validation_fails() throws Exception { // setup mock MultivaluedMap<String, String> params = getSimulatedParametersFromRegistrationResponse(); when(context.getHttpRequest().getDecodedFormParameters()).thenReturn(params); when(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE)).thenReturn("7777777777777777"); // test try { authenticator.processAction(context); Assert.fail(); } catch (AuthenticationFlowException e) { // NOP } }
Example #13
Source File: ClientCodeRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
protected MultivaluedMap<String, String> createRedirectState(ContainerRequestContext rc, UriInfo ui, MultivaluedMap<String, String> codeRequestState) { if (clientStateManager == null) { return new MetadataMap<String, String>(); } String codeVerifier = null; if (codeVerifierTransformer != null) { codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32)); codeRequestState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier); } MultivaluedMap<String, String> redirectState = clientStateManager.toRedirectState(mc, codeRequestState); if (codeVerifier != null) { redirectState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier); } return redirectState; }
Example #14
Source File: ValidateEndpoint.java From keycloak-protocol-cas with Apache License 2.0 | 6 votes |
@GET @NoCache public Response build() { MultivaluedMap<String, String> params = session.getContext().getUri().getQueryParameters(); String service = params.getFirst(CASLoginProtocol.SERVICE_PARAM); String ticket = params.getFirst(CASLoginProtocol.TICKET_PARAM); boolean renew = params.containsKey(CASLoginProtocol.RENEW_PARAM); event.event(EventType.CODE_TO_TOKEN); try { checkSsl(); checkRealm(); checkClient(service); checkTicket(ticket, renew); event.success(); return successResponse(); } catch (CASValidationException e) { return errorResponse(e); } }
Example #15
Source File: TrellisRequest.java From trellis with Apache License 2.0 | 6 votes |
public static String buildBaseUrl(final URI uri, final MultivaluedMap<String, String> headers) { // Start with the baseURI from the request final UriBuilder builder = UriBuilder.fromUri(uri); // Adjust the protocol, using the non-spec X-Forwarded-* header, if present final Forwarded nonSpec = new Forwarded(null, headers.getFirst("X-Forwarded-For"), headers.getFirst("X-Forwarded-Host"), headers.getFirst("X-Forwarded-Proto")); nonSpec.getHostname().ifPresent(builder::host); nonSpec.getPort().ifPresent(builder::port); nonSpec.getProto().ifPresent(builder::scheme); // The standard Forwarded header overrides these values final Forwarded forwarded = Forwarded.valueOf(headers.getFirst("Forwarded")); if (forwarded != null) { forwarded.getHostname().ifPresent(builder::host); forwarded.getPort().ifPresent(builder::port); forwarded.getProto().ifPresent(builder::scheme); } return builder.build().toString(); }
Example #16
Source File: SecurityWsTest.java From ipst with Mozilla Public License 2.0 | 6 votes |
@Test public void testWrongLimits() { MultipartFormDataInput dataInput = mock(MultipartFormDataInput.class); Map<String, List<InputPart>> formValues = new HashMap<>(); formValues.put("format", Collections.singletonList(new InputPartImpl("JSON", MediaType.TEXT_PLAIN_TYPE))); formValues.put("limit-types", Collections.singletonList(new InputPartImpl("ERRR", MediaType.TEXT_PLAIN_TYPE))); MultivaluedMap<String, String> headers = new MultivaluedMapImpl<>(); headers.putSingle("Content-Disposition", "filename=" + "case-file.xiidm.gz"); formValues.put("case-file", Collections.singletonList(new InputPartImpl(new ByteArrayInputStream("Network".getBytes()), MediaType.APPLICATION_OCTET_STREAM_TYPE, headers))); MultivaluedMap<String, String> headers2 = new MultivaluedMapImpl<>(); headers2.putSingle("Content-Disposition", "filename=" + "contingencies-file.csv"); formValues.put("contingencies-file", Collections.singletonList(new InputPartImpl(new ByteArrayInputStream("contingencies".getBytes()), MediaType.APPLICATION_OCTET_STREAM_TYPE, headers2))); when(dataInput.getFormDataMap()).thenReturn(formValues); Response res = service.analyze(dataInput); Assert.assertEquals(400, res.getStatus()); }
Example #17
Source File: DelimitedWriter.java From SciGraph with Apache License 2.0 | 6 votes |
@Override public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException { try (Writer writer = new OutputStreamWriter(out); CSVPrinter printer = getCsvPrinter(writer)) { List<String> header = newArrayList("id", "label", "categories"); printer.printRecord(header); List<String> vals = new ArrayList<>(); for (Vertex vertex: data.getVertices()) { vals.clear(); vals.add(getCurieOrIri(vertex)); String label = getFirst(TinkerGraphUtil.getProperties(vertex, NodeProperties.LABEL, String.class), null); vals.add(label); vals.add(TinkerGraphUtil.getProperties(vertex, Concept.CATEGORY, String.class).toString()); printer.printRecord(vals); } } }
Example #18
Source File: QueryExecutorBeanTest.java From datawave with Apache License 2.0 | 6 votes |
private MultivaluedMap createNewQueryParameterMap() throws Exception { MultivaluedMap<String,String> p = new MultivaluedMapImpl<>(); p.putSingle(QueryParameters.QUERY_STRING, "foo == 'bar'"); p.putSingle(QueryParameters.QUERY_NAME, "query name"); p.putSingle(QueryParameters.QUERY_AUTHORIZATIONS, StringUtils.join(auths, ",")); p.putSingle(QueryParameters.QUERY_BEGIN, QueryParametersImpl.formatDate(beginDate)); p.putSingle(QueryParameters.QUERY_END, QueryParametersImpl.formatDate(endDate)); p.putSingle(QueryParameters.QUERY_EXPIRATION, QueryParametersImpl.formatDate(expirationDate)); p.putSingle(QueryParameters.QUERY_NAME, queryName); p.putSingle(QueryParameters.QUERY_PAGESIZE, Integer.toString(pagesize)); p.putSingle(QueryParameters.QUERY_STRING, query); p.putSingle(QueryParameters.QUERY_PERSISTENCE, persist.name()); p.putSingle(ColumnVisibilitySecurityMarking.VISIBILITY_MARKING, "PRIVATE|PUBLIC"); return p; }
Example #19
Source File: FHIRJsonProvider.java From FHIR with Apache License 2.0 | 6 votes |
@Override public void writeTo(JsonObject t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { log.entering(this.getClass().getName(), "writeTo"); try (JsonWriter writer = JSON_WRITER_FACTORY.createWriter(nonClosingOutputStream(entityStream))) { writer.writeObject(t); } catch (JsonException e) { // log the error but don't throw because that seems to block to original IOException from bubbling for some reason log.log(Level.WARNING, "an error occurred during resource serialization", e); if (RuntimeType.SERVER.equals(runtimeType)) { Response response = buildResponse( buildOperationOutcome(Collections.singletonList( buildOperationOutcomeIssue(IssueSeverity.FATAL, IssueType.EXCEPTION, "FHIRProvider: " + e.getMessage(), null))), mediaType); throw new WebApplicationException(response); } } finally { log.exiting(this.getClass().getName(), "writeTo"); } }
Example #20
Source File: RestfulWSMessageFactory.java From sdk-java with Apache License 2.0 | 5 votes |
public static MessageReader create(MediaType mediaType, MultivaluedMap<String, String> headers, byte[] payload) throws IllegalArgumentException { return MessageUtils.parseStructuredOrBinaryMessage( () -> headers.getFirst(HttpHeaders.CONTENT_TYPE), format -> new GenericStructuredMessageReader(format, payload), () -> headers.getFirst(CloudEventsHeaders.SPEC_VERSION), sv -> new BinaryRestfulWSMessageReaderImpl(sv, headers, payload), UnknownEncodingMessageReader::new ); }
Example #21
Source File: RequestLogger.java From qaf with MIT License | 5 votes |
private void printResponseHeaders(StringBuilder b, long id, MultivaluedMap<String, String> headers) { for (Map.Entry<String, List<String>> e : headers.entrySet()) { String header = e.getKey(); for (String value : e.getValue()) { prefixId(b, id).append(RESPONSE_PREFIX).append(header).append(": ").append(value).append("\n"); } } prefixId(b, id).append(RESPONSE_PREFIX).append("\n"); }
Example #22
Source File: MediaTypeExtension.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
@Override public void writeTo(final T object, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { final MessageBodyWriter<T> writer = writers.get(mediaTypeWithoutParams(mediaType)); if (writer != null) { writer.writeTo(object, type, genericType, annotations, mediaType, httpHeaders, entityStream); } else { throw new InternalServerErrorException("unsupported media type"); } }
Example #23
Source File: FormParameterResolverTest.java From everrest with Eclipse Public License 2.0 | 5 votes |
@Test public void throwsIllegalStateExceptionWhenFormMessageBodyReaderIsNotAvailable() throws Exception { Class<MultivaluedMap> type = MultivaluedMap.class; ParameterizedType genericType = newParameterizedType(type, String.class, String.class); when(applicationContext.getProviders().getMessageBodyReader(eq(type), eq(genericType), any(), eq(APPLICATION_FORM_URLENCODED_TYPE))) .thenReturn(null); thrown.expect(IllegalStateException.class); formParameterResolver.resolve(parameter, applicationContext); }
Example #24
Source File: RawLoggingFilter.java From phoebus with Eclipse Public License 1.0 | 5 votes |
private void printRequestHeaders(StringBuilder b, long id, MultivaluedMap<String, Object> headers) { for (Map.Entry<String, List<Object>> e : headers.entrySet()) { String header = e.getKey(); for (Object value : e.getValue()) { prefixId(b, id).append(REQUEST_PREFIX).append(header) .append(": ") .append(ClientRequest.getHeaderValue(value)) .append("\n"); } } prefixId(b, id).append(REQUEST_PREFIX).append("\n"); }
Example #25
Source File: UriInfoImpl.java From cxf with Apache License 2.0 | 5 votes |
public UriInfoImpl(Message m, MultivaluedMap<String, String> templateParams) { this.message = m; this.templateParams = templateParams; if (m != null) { this.stack = m.get(OperationResourceInfoStack.class); this.caseInsensitiveQueries = MessageUtils.getContextualBoolean(m, CASE_INSENSITIVE_QUERIES); this.queryValueIsCollection = MessageUtils.getContextualBoolean(m, PARSE_QUERY_VALUE_AS_COLLECTION); } }
Example #26
Source File: JAXRSClientServerStreamingTest.java From cxf with Apache License 2.0 | 5 votes |
@Override public void writeTo(Object obj, Class<?> cls, Type genericType, Annotation[] anns, MediaType m, MultivaluedMap<String, Object> headers, OutputStream os) throws IOException { List<String> failHeaders = getContext().getHttpHeaders().getRequestHeader("fail-write"); if (failHeaders != null && !failHeaders.isEmpty()) { os.write("fail".getBytes()); throw new IOException(); } super.writeTo(obj, cls, genericType, anns, m, headers, os); }
Example #27
Source File: WebAcFilterTest.java From trellis with Apache License 2.0 | 5 votes |
@Test void testFilterResponseNoAuthorizationModes() { final MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); when(mockResponseContext.getStatusInfo()).thenReturn(OK); when(mockResponseContext.getHeaders()).thenReturn(headers); when(mockContext.getProperty(eq(WebAcFilter.SESSION_WEBAC_MODES))) .thenReturn(new Object()); final WebAcFilter filter = new WebAcFilter(); filter.setAccessService(mockWebAcService); assertTrue(headers.isEmpty()); filter.filter(mockContext, mockResponseContext); assertTrue(headers.isEmpty()); }
Example #28
Source File: JsonServiceNamesMarshaller.java From curator with Apache License 2.0 | 5 votes |
@Override public ServiceNames readFrom(Class<ServiceNames> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { List<String> names = Lists.newArrayList(); ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.reader().readTree(entityStream); for ( int i = 0; i < tree.size(); ++i ) { JsonNode node = tree.get(i); names.add(node.get("name").asText()); } return new ServiceNames(names); }
Example #29
Source File: DefaultUUIDModificationRequest.java From datawave with Apache License 2.0 | 5 votes |
@Override public MultivaluedMap<String,String> toMap() { MultivaluedMap<String,String> p = new MultivaluedMapImpl<String,String>(); p.putAll(super.toMap()); if (this.events != null) { for (ModificationEvent e : events) { p.add("Events", e.toString()); } } return p; }
Example #30
Source File: AbstractRestClient.java From hugegraph-common with Apache License 2.0 | 5 votes |
private Pair<Builder, Entity<?>> buildRequest( String path, String id, Object object, MultivaluedMap<String, Object> headers, Map<String, Object> params) { WebTarget target = this.target; if (params != null && !params.isEmpty()) { for (Map.Entry<String, Object> param : params.entrySet()) { target = target.queryParam(param.getKey(), param.getValue()); } } Builder builder = id == null ? target.path(path).request() : target.path(path).path(encode(id)).request(); String encoding = null; if (headers != null && !headers.isEmpty()) { // Add headers builder = builder.headers(headers); encoding = (String) headers.getFirst("Content-Encoding"); } /* * We should specify the encoding of the entity object manually, * because Entity.json() method will reset "content encoding = * null" that has been set up by headers before. */ Entity<?> entity; if (encoding == null) { entity = Entity.json(object); } else { Variant variant = new Variant(MediaType.APPLICATION_JSON_TYPE, (String) null, encoding); entity = Entity.entity(object, variant); } return Pair.of(builder, entity); }