private Plain asPlain(org.apache.http.HttpResponse response) throws IOException { assertThat(response.getStatusLine().getStatusCode(), is(200)); HttpEntity entity = response.getEntity(); MediaType mediaType = MediaType.parse(entity.getContentType().getValue()); assertThat(mediaType.type(), is("application")); assertThat(mediaType.subtype(), is("json")); return Jsons.toObject(entity.getContent(), Plain.class); }
@Override public void setContentType(String type) { if (isCommitted()) { return; } if (hasWriter()) { return; } if (null == type) { contentType = null; return; } MediaType mediaType = MediaType.parse(type); Optional<Charset> charset = mediaType.charset(); if (charset.isPresent()) { setCharacterEncoding(charset.get().name()); } contentType = mediaType.type() + '/' + mediaType.subtype(); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PProcessor processor = processorProvider.processorForRequest(req); try { Serializer requestSerializer = serializerProvider.getDefault(); if (req.getContentType() != null) { requestSerializer = serializerProvider.getSerializer(req.getContentType()); if (requestSerializer == null) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "Unknown content-type: " + req.getContentType()); return; } } Serializer responseSerializer = requestSerializer; String acceptHeader = resp.getHeader("Accept"); if (acceptHeader != null) { String[] entries = acceptHeader.split("[,]"); for (String entry : entries) { if (entry.trim().isEmpty()) { continue; } try { MediaType mediaType = MediaType.parse(entry.trim()); Serializer tmp = serializerProvider.getSerializer(mediaType.type() + "/" + mediaType.subtype()); if (tmp != null) { responseSerializer = tmp; break; } } catch (IllegalArgumentException ignore) { // Ignore. Bad header input is pretty common. } } if (responseSerializer == null) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "No supported accept media-type: " + acceptHeader); return; } } MessageReader reader = new IOMessageReader(req.getInputStream(), requestSerializer); ByteArrayOutputStream baos = new ByteArrayOutputStream(); MessageWriter writer = new IOMessageWriter(baos, responseSerializer); // Create a new processor handler instance for each request, as // they may be request context dependent. E.g. depends on // information in header, servlet context etc. new DefaultProcessorHandler(processor).process(reader, writer); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(responseSerializer.mimeType()); resp.setContentLength(baos.size()); resp.getOutputStream().write(baos.toByteArray()); } catch (Exception e) { LOGGER.error( "Exception in service call for " + processor.getDescriptor().getQualifiedName(), e); resp.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error: " + e.getMessage()); } }