@Override public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { final MediaType type = response.getMediaType(); if (type != null && !type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) { final MediaType typeWithCharset = type.withCharset(UTF_8); response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, typeWithCharset); } } }
private Response doGetRequest(String location, String auth, String query) { String url = String.format("%s?%s", location, query); Response r = this.client.target(url) .request() .header(HttpHeaders.AUTHORIZATION, auth) .accept(MediaType.APPLICATION_JSON) .acceptEncoding(CompressInterceptor.GZIP) .get(); if (r.getMediaType() != null) { // Append charset assert MediaType.APPLICATION_JSON_TYPE.equals(r.getMediaType()); r.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, r.getMediaType().withCharset(CHARSET)); } gremlinInputHistogram.update(query.length()); gremlinOutputHistogram.update(r.getLength()); return r; }
private Response doPostRequest(String location, String auth, String req) { Entity<?> body = Entity.entity(req, MediaType.APPLICATION_JSON); Response r = this.client.target(location) .request() .header(HttpHeaders.AUTHORIZATION, auth) .accept(MediaType.APPLICATION_JSON) .acceptEncoding(CompressInterceptor.GZIP) .post(body); if (r.getMediaType() != null) { // Append charset assert MediaType.APPLICATION_JSON_TYPE.equals(r.getMediaType()); r.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, r.getMediaType().withCharset(CHARSET)); } gremlinInputHistogram.update(req.length()); gremlinOutputHistogram.update(r.getLength()); return r; }
protected BrowserCache.Entry getEntry(ClientRequestContext request) throws Exception { String uri = request.getUri().toString(); List<MediaType> acceptableMediaTypes = request.getAcceptableMediaTypes(); BrowserCache.Entry entry = null; if (acceptableMediaTypes.size() > 0) { for (MediaType accept : acceptableMediaTypes) { entry = cache.get(uri, accept); if (entry != null) return entry; if (MediaTypeHelper.isTextLike(accept)) { entry = cache.get(uri, accept.withCharset("UTF-8")); if (entry != null) return entry; } } } else { return cache.getAny(uri); } return null; }
public static MediaType getResponseMediaType(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response, ResteasyProviderFactory providerFactory, ResourceMethodInvoker method) { MediaType mt = null; if (!jaxrsResponse.isClosed() && jaxrsResponse.getEntity() != null) { if ((mt = jaxrsResponse.getMediaType()) == null) { mt = getDefaultContentType(request, jaxrsResponse, providerFactory, method); } boolean addCharset = true; ResteasyDeployment deployment = ResteasyContext.getContextData(ResteasyDeployment.class); if (deployment != null) { addCharset = deployment.isAddCharset(); } if (addCharset) { if (!mt.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) { if (MediaTypeHelper.isTextLike(mt)) { mt = mt.withCharset(StandardCharsets.UTF_8.toString()); } } } } return mt; }
@Override public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE.withCharset(StandardCharsets.UTF_8.name())); t.storeToXML(entityStream, null); }
private String guessMimeType(final String filename, final Boolean isUTF8) { MediaType mediaType = APPLICATION_OCTET_STREAM_TYPE; String guessedMimeType = context.getMimeType(filename.toString()); if (guessedMimeType != null) { mediaType = valueOf(guessedMimeType); } if (isUTF8 != null && isUTF8) { mediaType = mediaType.withCharset(StandardCharsets.UTF_8.name()); } return mediaType.toString(); }
public static Response createResponse(Response.Status status, MediaType mediaType, CASServiceResponse serviceResponse) { Response.ResponseBuilder builder = Response.status(status) .header(HttpHeaders.CONTENT_TYPE, mediaType.withCharset("utf-8")); if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { return builder.entity(ServiceResponseMarshaller.marshalJson(serviceResponse)).build(); } else { return builder.entity(ServiceResponseMarshaller.marshalXml(serviceResponse)).build(); } } }
@Override public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset(StandardCharsets.UTF_8.name())); final Type mapType = new TypeToken<Map<String, String>>() { private static final long serialVersionUID = 1L; }.getType(); Map<String, String> writeMap = t.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString())); String json = new GsonBuilder().registerTypeAdapter(mapType, new BundleMapSerializer()) .create() .toJson(writeMap, mapType); entityStream.write(json.getBytes(StandardCharsets.UTF_8)); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(MediaType.TEXT_HTML_TYPE.withCharset(UTF_8.name()).toString()); response.setStatus(200); PushBuilder builder = request.newPushBuilder(); // If server push isn't supported, return that in the result. if (builder == null) { response.addHeader("protocol", "HTTP 1.1"); response.getWriter().append("<p>The image below was sent normally using HTTP 1.1.</p>"); } else { response.addHeader("protocol", "HTTP/2"); response.getWriter().append("<p>The image below was pushed using HTTP/2.</p>"); builder.path("images/payara-logo.jpg").push(); } response.getWriter().append("<img src=\"images/payara-logo.jpg\" />"); }
@Override public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { final MediaType type = response.getMediaType(); if (type != null && !type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) { final MediaType typeWithCharset = type.withCharset(UTF_8); response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, typeWithCharset); } } }
protected Response createJsonResponse(QueryResponse queryResponse) { try { return buildResponse(Response.ok(jsonObjectWriter.writeValueAsString(queryResponse), MediaType.APPLICATION_JSON_TYPE.withCharset("utf-8"))); } catch (JsonProcessingException e) { e.printStackTrace(); logger.error("Error parsing queryResponse object"); return createErrorResponse("", "Error parsing QueryResponse object:\n" + Arrays.toString(e.getStackTrace())); } }
@Test public void directOkComplexContentType() { Form form = new Form(); form.param("username", "foo"); form.param("password", "foo"); final String ok = container.getTarget("/direct").request().post( Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE.withCharset("UTF-8")), String.class); assertThat(ok).isEqualTo("ok"); }
@Override public void writeTo(Model model, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { Evaluator evaluator = model.getEvaluator(); HasPMML hasPMML = (HasPMML)evaluator; httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8")); httpHeaders.putSingle(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=model.pmml.xml"); // XXX PMML pmml = hasPMML.getPMML(); try { Result result = new StreamResult(entityStream); Marshaller marshaller = JAXBUtil.createMarshaller(); marshaller.marshal(pmml, result); } catch(JAXBException je){ throw new InternalServerErrorException(je); } }
/** * This methods reads the 'charset' parameter from the media type and falls back to 'UTF-8' * if the parameter is missing. It then adds a corresponding 'Content-Type' with the correct * encoding to the response headers. Finally it returns the effective character set so that * the view engine implementation can use it write the data correctly to the output stream. * * @param context The context * @return the effective charset */ protected Charset resolveCharsetAndSetContentType(ViewEngineContext context) { String charset = context.getMediaType().getParameters().get("charset"); if (charset == null) { charset = "UTF-8"; } MediaType mediaType = context.getMediaType().withCharset(charset); context.getResponseHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString()); return Charset.forName(charset); }
static Variant textResponseVariant() { return Variant. languages(Locale.ENGLISH). mediaTypes(MediaType.TEXT_PLAIN_TYPE.withCharset(StandardCharsets.UTF_8.name())). add(). build(). get(0); }
@Override public void writeTo(TableEvaluationResponse tableResponse, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { TableFormat tableFormat = tableResponse.getFormat(); String charset = tableFormat.getCharset(); if(charset == null){ charset = "UTF-8"; } httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_TYPE.withCharset(charset)); httpHeaders.putSingle(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=results.csv"); // XXX BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(entityStream, charset)){ @Override public void close() throws IOException { flush(); // The closing of the underlying java.io.OutputStream is handled elsewhere } }; try { CsvPreference format = CsvUtil.createFormat(tableFormat.getDelimiterChar(), tableFormat.getQuoteChar()); CsvUtil.writeTable(tableResponse, writer, format); } finally { writer.close(); } }
import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MediaType; public class CharsetResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { MediaType type = response.getMediaType(); if (type != null) { if (!type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) { MediaType typeWithCharset = type.withCharset("utf-8"); response.getHeaders().putSingle("Content-Type", typeWithCharset); } } } }
protected Response getRequest(int requestId, List<MediaType> accept) throws SQLException, IOException, NotFoundException{ MediaType[] available = getTypeManager().createMediaTypes(getBroker().getRequestTypes(requestId)); if( available.length == 0 ){ throw new NotFoundException(); } // find acceptable request definition RequestConverter rc = getTypeManager().buildConverterChain(accept, Arrays.asList(available)); if( rc == null ){ // no acceptable response type available return Response.notAcceptable(Variant.mediaTypes(available).build()).build(); }else{ Reader def = getBroker().getRequestDefinition(requestId, rc.getConsumedType()); // transform def = rc.transform(def); // output using UTF-8. The HTTP default charset ISO-8859-1 has some missing characters like e.g Euro sign. return Response.ok(def, MediaType.valueOf(rc.getProducedType()).withCharset("UTF-8")).build(); } }
@Override public Variant expectedVariant() { List<Variant> variants=VariantUtils.defaultVariants(); Variant variant=this.request.selectVariant(variants); if(variant==null) { throw new NotAcceptableException(this); } String acceptableCharset=acceptedCharset(); if(acceptableCharset==null) { throw new NotAcceptableException(this); } return Variant. encodings(variant.getEncoding()). languages(variant.getLanguage()). mediaTypes(variant.getMediaType().withCharset(acceptableCharset)). add(). build(). get(0); }