protected <T> void writeBody( T o, Message outMessage, Class<?> cls, Type type, Annotation[] anns, OutputStream os) { if (o == null) { return; } @SuppressWarnings("unchecked") MultivaluedMap<String, Object> headers = (MultivaluedMap<String, Object>) outMessage.get(Message.PROTOCOL_HEADERS); @SuppressWarnings("unchecked") Class<T> theClass = (Class<T>) cls; MediaType contentType = JAXRSUtils.toMediaType(headers.getFirst("Content-Type").toString()); List<WriterInterceptor> writers = ClientProviderFactory.getInstance(outMessage) .createMessageBodyWriterInterceptor( theClass, type, anns, contentType, outMessage, null); if (writers != null) { try { JAXRSUtils.writeMessageBody( writers, o, theClass, type, anns, contentType, headers, outMessage); OutputStream realOs = outMessage.get(OutputStream.class); if (realOs != null) { realOs.flush(); } } catch (Exception ex) { reportMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, contentType, ex); } } else { reportMessageHandlerProblem("NO_MSG_WRITER", cls, contentType, null); } }
public MultivaluedMap<String, String> getQueryParameters(boolean decode) { if (!caseInsensitiveQueries) { return JAXRSUtils.getStructuredParams( (String) message.get(Message.QUERY_STRING), "&", decode, decode); } MultivaluedMap<String, String> queries = new MetadataMap<String, String>(false, true); JAXRSUtils.getStructuredParams( queries, (String) message.get(Message.QUERY_STRING), "&", decode, decode); return queries; }
public void filter(ContainerRequestContext context) { try { interceptor.handleMessage(JAXRSUtils.getCurrentMessage()); } catch (AccessDeniedException ex) { context.abortWith(Response.status(Response.Status.FORBIDDEN).build()); } }
private void processResponse(ServerProviderFactory providerFactory, Message message) { if (isResponseAlreadyHandled(message)) { return; } MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs == null || objs.size() == 0) { return; } Object responseObj = objs.get(0); Response response = null; if (responseObj instanceof Response) { response = (Response) responseObj; if (response.getStatus() == 500 && message.getExchange().get(JAXRSUtils.EXCEPTION_FROM_MAPPER) != null) { message.put(Message.RESPONSE_CODE, 500); return; } } else { int status = getStatus(message, responseObj != null ? 200 : 204); response = JAXRSUtils.toResponseBuilder(status).entity(responseObj).build(); } Exchange exchange = message.getExchange(); OperationResourceInfo ori = (OperationResourceInfo) exchange.get(OperationResourceInfo.class.getName()); serializeMessage(providerFactory, message, response, ori, true); }
private MultivaluedMap<String, String> setRequestHeaders( MultivaluedMap<String, String> headers, OperationResourceInfo ori, boolean formParams, Class<?> bodyClass, Class<?> responseClass) { if (headers.getFirst(HttpHeaders.CONTENT_TYPE) == null) { if (formParams || bodyClass != null && MultivaluedMap.class.isAssignableFrom(bodyClass)) { headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); } else { String ctType = null; List<MediaType> consumeTypes = ori.getConsumeTypes(); if (!consumeTypes.isEmpty() && !consumeTypes.get(0).equals(MediaType.WILDCARD_TYPE)) { ctType = JAXRSUtils.mediaTypeToString(ori.getConsumeTypes().get(0)); } else if (bodyClass != null) { ctType = MediaType.APPLICATION_XML; } if (ctType != null) { headers.putSingle(HttpHeaders.CONTENT_TYPE, ctType); } } } List<MediaType> accepts = getAccept(headers); if (accepts == null) { boolean produceWildcard = ori.getProduceTypes().size() == 0 || ori.getProduceTypes().get(0).equals(MediaType.WILDCARD_TYPE); if (produceWildcard) { accepts = InjectionUtils.isPrimitive(responseClass) ? Collections.singletonList(MediaType.TEXT_PLAIN_TYPE) : Collections.singletonList(MediaType.APPLICATION_XML_TYPE); } else if (responseClass == Void.class || responseClass == Void.TYPE) { accepts = Collections.singletonList(MediaType.WILDCARD_TYPE); } else { accepts = ori.getProduceTypes(); } for (MediaType mt : accepts) { headers.add(HttpHeaders.ACCEPT, JAXRSUtils.mediaTypeToString(mt)); } } return headers; }
private List<MediaType> getAccept(MultivaluedMap<String, String> allHeaders) { List<String> headers = allHeaders.get(HttpHeaders.ACCEPT); if (headers == null || headers.size() == 0) { return null; } List<MediaType> types = new ArrayList<MediaType>(); for (String s : headers) { types.add(JAXRSUtils.toMediaType(s)); } return types; }
private MediaType getResponseMediaType(Object mediaTypeHeader) { MediaType responseMediaType; if (mediaTypeHeader instanceof MediaType) { responseMediaType = (MediaType) mediaTypeHeader; } else { responseMediaType = mediaTypeHeader == null ? MediaType.WILDCARD_TYPE : JAXRSUtils.toMediaType(mediaTypeHeader.toString()); } return responseMediaType; }
private void writeResponseErrorMessage( Message message, OutputStream out, String name, Class<?> cls, MediaType ct) { message.put(Message.CONTENT_TYPE, "text/plain"); message.put(Message.RESPONSE_CODE, 500); try { String errorMessage = JAXRSUtils.logMessageHandlerProblem(name, cls, ct); if (out != null) { out.write(errorMessage.getBytes(StandardCharsets.UTF_8)); } } catch (IOException another) { // ignore } }
private MediaType checkFinalContentType( MediaType mt, List<WriterInterceptor> writers, boolean checkWriters) { if (checkWriters) { int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1; MessageBodyWriter<Object> writer = ((WriterInterceptorMBW) writers.get(mbwIndex)).getMBW(); Produces pm = writer.getClass().getAnnotation(Produces.class); if (pm != null) { List<MediaType> sorted = JAXRSUtils.sortMediaTypes( JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM); mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0); } } if (mt.isWildcardType() || mt.isWildcardSubtype()) { if ("application".equals(mt.getType()) || mt.isWildcardType()) { mt = MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { throw ExceptionUtils.toNotAcceptableException(null, null); } } return mt; }
protected MultivaluedMap<String, String> toRequestState(ContainerRequestContext rc, UriInfo ui) { MultivaluedMap<String, String> requestState = new MetadataMap<String, String>(); requestState.putAll(ui.getQueryParameters(decodeRequestParameters)); if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(rc.getMediaType())) { String body = FormUtils.readBody(rc.getEntityStream(), StandardCharsets.UTF_8.name()); FormUtils.populateMapFromString( requestState, JAXRSUtils.getCurrentMessage(), body, StandardCharsets.UTF_8.name(), decodeRequestParameters); } return requestState; }
private void addXslProcessingInstruction(Marshaller ms, MediaType mt, XSLTTransform ann) throws Exception { if (ann.type() == XSLTTransform.TransformType.CLIENT || ann.type() == XSLTTransform.TransformType.BOTH && ann.mediaTypes().length > 0) { for (String s : ann.mediaTypes()) { if (mt.isCompatible(JAXRSUtils.toMediaType(s))) { return; } } String absRef = resolveXMLResourceURI(ann.value()); String xslPi = "<?xml-stylesheet type=\"text/xsl\" href=\"" + absRef + "\"?>"; setXmlPiProperty(ms, xslPi); } }
private void handleWriteException( ServerProviderFactory pf, Message message, Throwable ex, boolean firstTry) { Response excResponse = null; if (firstTry) { excResponse = JAXRSUtils.convertFaultToResponse(ex, message); } else { message.getExchange().put(JAXRSUtils.SECOND_JAXRS_EXCEPTION, Boolean.TRUE); } if (excResponse == null) { setResponseStatus(message, 500); throw new Fault(ex); } else { serializeMessage(pf, message, excResponse, null, false); } }
protected XSLTTransform getXsltTransformAnn(Annotation[] anns, MediaType mt) { XSLTTransform ann = AnnotationUtils.getAnnotation(anns, XSLTTransform.class); if (ann != null && ann.type() != XSLTTransform.TransformType.CLIENT) { if (ann.mediaTypes().length > 0) { for (String s : ann.mediaTypes()) { if (mt.isCompatible(JAXRSUtils.toMediaType(s))) { return ann; } } return null; } return ann; } return null; }
private void setAtHashAndNonce(IdToken idToken, ServerAccessToken st) { if (idToken.getAccessTokenHash() == null) { Properties props = JwsUtils.loadSignatureOutProperties(false); SignatureAlgorithm sigAlgo = null; if (super.isSignWithClientSecret()) { sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props); } else { sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256); } if (sigAlgo != SignatureAlgorithm.NONE) { String atHash = OidcUtils.calculateAccessTokenHash(st.getTokenKey(), sigAlgo); idToken.setAccessTokenHash(atHash); } } Message m = JAXRSUtils.getCurrentMessage(); if (m != null && m.getExchange().containsKey(OAuthConstants.NONCE)) { idToken.setNonce((String) m.getExchange().get(OAuthConstants.NONCE)); } else if (st.getNonce() != null) { idToken.setNonce(st.getNonce()); } }
private void logWriteError(boolean firstTry, Class<?> cls, MediaType ct) { if (firstTry) { JAXRSUtils.logMessageHandlerProblem("MSG_WRITER_PROBLEM", cls, ct); } }
private void serializeMessage( ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) { ResponseImpl response = (ResponseImpl) JAXRSUtils.copyResponseIfNeeded(theResponse); final Exchange exchange = message.getExchange(); boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod()); Object entity = response.getActualEntity(); if (headResponse && entity != null) { LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString()); entity = null; } Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke(); Annotation[] annotations = null; Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[] {}; Annotation[] responseAnns = response.getEntityAnnotations(); if (responseAnns != null) { annotations = new Annotation[staticAnns.length + responseAnns.length]; System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length); System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length); } else { annotations = staticAnns; } response.setStatus(getActualStatus(response.getStatus(), entity)); response.setEntity(entity, annotations); // Prepare the headers MultivaluedMap<String, Object> responseHeaders = prepareResponseHeaders(message, response, entity, firstTry); // Run the filters try { JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } // Write the entity entity = InjectionUtils.getEntity(response.getActualEntity()); setResponseStatus(message, getActualStatus(response.getStatus(), entity)); if (entity == null) { if (!headResponse) { responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0"); if (MessageUtils.getContextualBoolean( message, "remove.content.type.for.empty.response", false)) { responseHeaders.remove(HttpHeaders.CONTENT_TYPE); message.remove(Message.CONTENT_TYPE); } } HttpUtils.convertHeaderValuesToString(responseHeaders, true); return; } Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS); boolean ignoreWriters = ignoreWritersProp == null ? false : Boolean.valueOf(ignoreWritersProp.toString()); if (ignoreWriters) { writeResponseToStream(message.getContent(OutputStream.class), entity); return; } MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE)); Class<?> serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null; Class<?> targetType = InjectionUtils.getRawResponseClass(entity); Type genericType = InjectionUtils.getGenericResponseType( invoked, serviceCls, response.getActualEntity(), targetType, exchange); targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType); annotations = response.getEntityAnnotations(); List<WriterInterceptor> writers = providerFactory.createMessageBodyWriterInterceptor( targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings()); OutputStream outOriginal = message.getContent(OutputStream.class); if (writers == null || writers.isEmpty()) { writeResponseErrorMessage( message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType); return; } try { boolean checkWriters = false; if (responseMediaType.isWildcardSubtype()) { Produces pM = AnnotationUtils.getMethodAnnotation( ori == null ? null : ori.getAnnotatedMethod(), Produces.class); Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class); checkWriters = pM == null && pC == null; } responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters); } catch (Throwable ex) { handleWriteException(providerFactory, message, ex, firstTry); return; } String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Response content type is: " + finalResponseContentType); } responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType); message.put(Message.CONTENT_TYPE, finalResponseContentType); boolean enabled = checkBufferingMode(message, writers, firstTry); try { try { JAXRSUtils.writeMessageBody( writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message); if (isResponseRedirected(message)) { return; } checkCachedStream(message, outOriginal, enabled); } finally { if (enabled) { OutputStream os = message.getContent(OutputStream.class); if (os != outOriginal && os instanceof CachedOutputStream) { os.close(); } message.setContent(OutputStream.class, outOriginal); message.put(XMLStreamWriter.class.getName(), null); } } } catch (Throwable ex) { logWriteError(firstTry, targetType, responseMediaType); handleWriteException(providerFactory, message, ex, firstTry); } }
protected ResponseBuilder setResponseBuilder(Message outMessage, Exchange exchange) throws Exception { Response response = exchange.get(Response.class); if (response != null) { outMessage .getExchange() .getInMessage() .put(Message.PROTOCOL_HEADERS, response.getStringHeaders()); return JAXRSUtils.fromResponse(JAXRSUtils.copyResponseIfNeeded(response)); } Integer status = getResponseCode(exchange); ResponseBuilder currentResponseBuilder = JAXRSUtils.toResponseBuilder(status); Message responseMessage = exchange.getInMessage() != null ? exchange.getInMessage() : exchange.getInFaultMessage(); // if there is no response message, we just send the response back directly if (responseMessage == null) { return currentResponseBuilder; } Map<String, List<Object>> protocolHeaders = CastUtils.cast((Map<?, ?>) responseMessage.get(Message.PROTOCOL_HEADERS)); boolean splitHeaders = MessageUtils.isTrue(outMessage.getContextualProperty(HEADER_SPLIT_PROPERTY)); for (Map.Entry<String, List<Object>> entry : protocolHeaders.entrySet()) { if (null == entry.getKey()) { continue; } if (entry.getValue().size() > 0) { if (HttpUtils.isDateRelatedHeader(entry.getKey())) { currentResponseBuilder.header(entry.getKey(), entry.getValue().get(0)); continue; } for (Object valObject : entry.getValue()) { if (splitHeaders && valObject instanceof String) { String val = (String) valObject; String[] values; if (val == null || val.length() == 0) { values = new String[] {""}; } else if (val.charAt(0) == '"' && val.charAt(val.length() - 1) == '"') { // if the value starts with a quote and ends with a quote, we do a best // effort attempt to determine what the individual values are. values = parseQuotedHeaderValue(val); } else { boolean splitPossible = !(HttpHeaders.SET_COOKIE.equalsIgnoreCase(entry.getKey()) && val.toUpperCase().contains(HttpHeaders.EXPIRES.toUpperCase())); values = splitPossible ? val.split(",") : new String[] {val}; } for (String s : values) { String theValue = s.trim(); if (theValue.length() > 0) { currentResponseBuilder.header(entry.getKey(), theValue); } } } else { currentResponseBuilder.header(entry.getKey(), valObject); } } } } String ct = (String) responseMessage.get(Message.CONTENT_TYPE); if (ct != null) { currentResponseBuilder.type(ct); } InputStream mStream = responseMessage.getContent(InputStream.class); currentResponseBuilder.entity(mStream); return currentResponseBuilder; }
public List<PathSegment> getPathSegments(boolean decode) { return JAXRSUtils.getPathSegments(getPath(false), decode); }
protected static void reportMessageHandlerProblem( String name, Class<?> cls, MediaType ct, Throwable cause) { String errorMessage = JAXRSUtils.logMessageHandlerProblem("NO_MSG_WRITER", cls, ct); throw new ProcessingException(errorMessage, cause); }
/** {@inheritDoc} */ public Client accept(MediaType... types) { for (MediaType mt : types) { possiblyAddHeader(HttpHeaders.ACCEPT, JAXRSUtils.mediaTypeToString(mt)); } return this; }
private void setClientCodeRequest(ClientTokenContext request) { JAXRSUtils.getCurrentMessage().setContent(ClientTokenContext.class, request); }
public T readFrom( Class<T> type, Type genericType, Annotation[] anns, MediaType mt, MultivaluedMap<String, String> headers, InputStream is) throws IOException { if (isPayloadEmpty(headers)) { if (AnnotationUtils.getAnnotation(anns, Nullable.class) != null) { return null; } else { reportEmptyContentLength(); } } XMLStreamReader reader = null; Unmarshaller unmarshaller = null; try { boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(type); Class<?> theGenericType = isCollection ? InjectionUtils.getActualType(genericType) : type; Class<?> theType = getActualType(theGenericType, genericType, anns); unmarshaller = createUnmarshaller(theType, genericType, isCollection); addAttachmentUnmarshaller(unmarshaller); Object response = null; if (JAXBElement.class.isAssignableFrom(type) || !isCollection && (unmarshalAsJaxbElement || jaxbElementClassMap != null && jaxbElementClassMap.containsKey(theType.getName()))) { reader = getStreamReader(is, type, mt); reader = TransformUtils.createNewReaderIfNeeded(reader, is); if (JAXBElement.class.isAssignableFrom(type) && type == theType) { response = unmarshaller.unmarshal(reader); } else { response = unmarshaller.unmarshal(reader, theType); } } else { response = doUnmarshal(unmarshaller, type, is, anns, mt); } if (response instanceof JAXBElement && !JAXBElement.class.isAssignableFrom(type)) { response = ((JAXBElement<?>) response).getValue(); } if (isCollection) { response = ((CollectionWrapper) response) .getCollectionOrArray( unmarshaller, theType, type, genericType, org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theGenericType, anns)); } else { response = checkAdapter(response, type, anns, false); } return type.cast(response); } catch (JAXBException e) { handleJAXBException(e, true); } catch (DepthExceededStaxException e) { throw ExceptionUtils.toWebApplicationException(null, JAXRSUtils.toResponse(413)); } catch (WebApplicationException e) { throw e; } catch (Exception e) { LOG.warning(ExceptionUtils.getStackTrace(e)); throw ExceptionUtils.toBadRequestException(e, null); } finally { try { StaxUtils.close(reader); } catch (XMLStreamException e) { // Ignore } JAXBUtils.closeUnmarshaller(unmarshaller); } // unreachable return null; }
/** {@inheritDoc} */ public Client type(MediaType ct) { return type(JAXRSUtils.mediaTypeToString(ct)); }