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: BinaryDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: AbstractTokenService.java    From cxf with Apache License 2.0 6 votes vote down vote up
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: QueryExecutorBeanTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: VirtualInstanceCollectionMessageBodyWriter.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@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 #5
Source File: FHIRJsonProvider.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: DelimitedWriter.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: SecurityWsTest.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@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 #9
Source File: TrellisRequest.java    From trellis with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: ValidateEndpoint.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: RegisterAuthenticatorTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
@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: SchemaRegistryResource.java    From registry with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: BasedModelProvider.java    From Processor with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: PropertyFilteringMessageBodyWriter.java    From jackson-jaxrs-propertyfiltering with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: DownloadFileResponseFilter.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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 #17
Source File: LogoutService.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
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 #18
Source File: SchemaRegistryResource.java    From registry with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #20
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
public int[] readFrom(Class<int[]> arg0, Type arg1,
    Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> arg4, InputStream arg5)
    throws IOException, WebApplicationException {
    String[] stringArr = IOUtils.readStringFromStream(arg5).split(",");
    int[] intArr = new int[stringArr.length];
    for (int i = 0; i < stringArr.length; i++) {
        intArr[i] = Integer.valueOf(stringArr[i]);
    }
    return intArr;

}
 
Example #21
Source File: BufferPublisherMessageBodyReaderWriter.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Buffer> readFrom(final Class<Publisher<Buffer>> type,
                                  final Type genericType,
                                  final Annotation[] annotations,
                                  final MediaType mediaType,
                                  final MultivaluedMap<String, String> httpHeaders,
                                  final InputStream entityStream) throws WebApplicationException {
    return readFrom(entityStream, (p, a) -> p, PublisherSource::new);
}
 
Example #22
Source File: AmbariServiceNodeDiscoverer.java    From streamline with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> readFrom(Class<Map> aClass, Type type,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> multivaluedMap, InputStream inputStream)
    throws IOException, WebApplicationException {
  return objectMapper.readValue(inputStream, aClass);
}
 
Example #23
Source File: URITemplateTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpressionWithNestedGroup2() throws Exception {
    URITemplate uriTemplate =
        new URITemplate("/{resource:.+\\.(js|css|gif|png)}/bar");
    MultivaluedMap<String, String> values = new MetadataMap<>();

    assertTrue(uriTemplate.match("/script.js/bar/baz", values));
    assertEquals("script.js", values.getFirst("resource"));
    String finalPath = values.getFirst(URITemplate.FINAL_MATCH_GROUP);
    assertEquals("/baz", finalPath);
}
 
Example #24
Source File: TestsendformdataException.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public TestsendformdataException(int statusCode, String reason, MultivaluedMap<String, String> headers, Response response) {
    super(reason);
    this.statusCode = statusCode;
    this.reason = reason;
    this.headers = headers;
    this.response = response;
}
 
Example #25
Source File: PrettyPrintFilter.java    From Alpine with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectWriter modify(EndpointConfigBase<?> endpointConfigBase, MultivaluedMap<String, Object> multivaluedMap,
                           Object o, ObjectWriter objectWriter, JsonGenerator jsonGenerator) throws IOException {

    jsonGenerator.useDefaultPrettyPrinter();
    return objectWriter;
}
 
Example #26
Source File: ListMultipartFormDataMessageBodyReader.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<InputItem> readFrom(Class<List<InputItem>> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                                MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    final Type fileItemIteratorGenericType = ParameterizedTypeImpl.newParameterizedType(Iterator.class, FileItem.class);
    final MessageBodyReader<Iterator> multipartReader =
            providers.getMessageBodyReader(Iterator.class, fileItemIteratorGenericType, annotations, mediaType);
    final Iterator iterator =
            multipartReader.readFrom(Iterator.class, fileItemIteratorGenericType, annotations, mediaType, httpHeaders, entityStream);
    final List<InputItem> result = new LinkedList<>();
    while (iterator.hasNext()) {
        result.add(new DefaultInputItem((FileItem)iterator.next(), providers));
    }
    return result;
}
 
Example #27
Source File: GsonMessageBodyHandler.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public void writeTo(Object object, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> stringObjectMultivaluedMap, OutputStream entityStream)
        throws IOException, WebApplicationException {

    OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
    try {
        getGson().toJson(object, type, writer);
    } finally {
        writer.close();
    }
}
 
Example #28
Source File: ClientRequestContextWrapperTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void putHeader() {
  MultivaluedMap<String, Object> headers = new Headers<>();
  when(request.getHeaders()).thenReturn(headers);

  new ClientRequestContextWrapper(request).header("name", "value");

  assertThat(headers).containsExactly(entry("name", Collections.singletonList("value")));
}
 
Example #29
Source File: WSUtils.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * @param uriInfo {@link UriInfo} from where to extract query parameters
 * @param queryParams {@link List<QueryParam>} to  where add the query parameters extracted from {@link UriInfo}
 * @return the updated  {@link List<QueryParam>} passed in the queryParams parameter
 * @throws NullPointerException if queryParams is null
 */
public static List<QueryParam> addQueryParams(UriInfo uriInfo, List<QueryParam> queryParams) {
    if (uriInfo != null) {
        MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
        if (!params.isEmpty()) {
            queryParams.addAll(WSUtils.buildQueryParameters(params));
        }
    }
    return queryParams;
}
 
Example #30
Source File: CharsetResponseFilter.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
      throws IOException {
	MultivaluedMap<String, Object> headers = responseContext.getHeaders();
	MediaType type = responseContext.getMediaType();
	if (type != null) {
		if (!type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) {
			MediaType typeWithCharset = type.withCharset("utf-8");
			headers.putSingle("Content-Type", typeWithCharset);
		}
	}
}