下面列出了javax.ws.rs.core.UriBuilderException#org.apache.cxf.jaxrs.utils.HttpUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void writeTo(String obj, Class<?> type, Type genType, Annotation[] anns,
MediaType mt, MultivaluedMap<String, Object> headers,
OutputStream os) throws IOException {
String encoding = HttpUtils.getSetEncoding(mt, headers, StandardCharsets.UTF_8.name());
//REVISIT try to avoid instantiating the whole byte array
byte[] bytes = obj.getBytes(encoding);
if (bytes.length > bufferSize) {
int pos = 0;
while (pos < bytes.length) {
int bl = bytes.length - pos;
if (bl > bufferSize) {
bl = bufferSize;
}
os.write(bytes, pos, bl);
pos += bl;
}
} else {
os.write(bytes);
}
}
private ResponseBuilder evaluateIfModifiedSince(Date lastModified) {
List<String> ifModifiedSince = headers.getRequestHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifModifiedSince == null || ifModifiedSince.isEmpty()) {
return null;
}
SimpleDateFormat dateFormat = HttpUtils.getHttpDateFormat();
dateFormat.setLenient(false);
Date dateSince = null;
try {
dateSince = dateFormat.parse(ifModifiedSince.get(0));
} catch (ParseException ex) {
// invalid header value, request should continue
return Response.status(Response.Status.PRECONDITION_FAILED);
}
if (dateSince.before(lastModified)) {
// request should continue
return null;
}
return Response.status(Response.Status.NOT_MODIFIED);
}
private ResponseBuilder evaluateIfNotModifiedSince(Date lastModified) {
List<String> ifNotModifiedSince = headers.getRequestHeader(HttpHeaders.IF_UNMODIFIED_SINCE);
if (ifNotModifiedSince == null || ifNotModifiedSince.isEmpty()) {
return null;
}
SimpleDateFormat dateFormat = HttpUtils.getHttpDateFormat();
dateFormat.setLenient(false);
Date dateSince = null;
try {
dateSince = dateFormat.parse(ifNotModifiedSince.get(0));
} catch (ParseException ex) {
// invalid header value, request should continue
return Response.status(Response.Status.PRECONDITION_FAILED);
}
if (dateSince.before(lastModified)) {
return Response.status(Response.Status.PRECONDITION_FAILED);
}
return null;
}
@Override
public String toString(String s) {
if (encodeClientParametersList == null || encodeClientParametersList.isEmpty()) {
return HttpUtils.urlEncode(s);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
if (encodeClientParametersList.contains(ch)) {
sb.append(HttpUtils.urlEncode(ch.toString()));
} else {
sb.append(ch);
}
}
return sb.toString();
}
public List<String> getRequestHeader(String name) {
boolean splitIndividualValue
= MessageUtils.getContextualBoolean(message, HEADER_SPLIT_PROPERTY, false);
List<String> values = headers.get(name);
if (!splitIndividualValue
|| values == null
|| HttpUtils.isDateRelatedHeader(name)) {
return values;
}
List<String> ls = new LinkedList<>();
for (String value : values) {
if (value == null) {
continue;
}
String sep = HttpHeaders.COOKIE.equalsIgnoreCase(name) ? getCookieSeparator(value) : DEFAULT_SEPARATOR;
ls.addAll(getHeaderValues(name, value, sep));
}
return ls;
}
@Test
public void testMultiLines() throws Exception {
String values = "foo=1+2&bar=line1%0D%0Aline+2&baz=4";
FormEncodingProvider<CustomMap> ferp = new FormEncodingProvider<>();
MultivaluedMap<String, String> mvMap = ferp.readFrom(CustomMap.class, null,
new Annotation[]{}, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null,
new ByteArrayInputStream(values.getBytes()));
assertEquals(3, mvMap.size());
assertEquals(1, mvMap.get("foo").size());
assertEquals(1, mvMap.get("bar").size());
assertEquals(1, mvMap.get("baz").size());
assertEquals("Wrong entry for foo", "1 2", mvMap.getFirst("foo"));
assertEquals("Wrong entry line for bar",
HttpUtils.urlDecode("line1%0D%0Aline+2"), mvMap.get("bar").get(0));
assertEquals("Wrong entry for baz", "4", mvMap.getFirst("baz"));
}
public void writeTo(T obj, Class<?> type, Type genericType, Annotation[] anns,
MediaType m, MultivaluedMap<String, Object> headers, OutputStream os)
throws IOException {
if (type == null) {
type = obj.getClass();
}
if (genericType == null) {
genericType = type;
}
AegisContext context = getAegisContext(type, genericType);
AegisType aegisType = context.getTypeMapping().getType(genericType);
AegisWriter<XMLStreamWriter> aegisWriter = context.createXMLStreamWriter();
try {
String enc = HttpUtils.getSetEncoding(m, headers, StandardCharsets.UTF_8.name());
XMLStreamWriter xmlStreamWriter = createStreamWriter(aegisType.getSchemaType(), enc, os);
// use type qname as element qname?
xmlStreamWriter.writeStartDocument();
aegisWriter.write(obj, aegisType.getSchemaType(), false, xmlStreamWriter, aegisType);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
} catch (Exception e) {
throw ExceptionUtils.toInternalServerErrorException(e, null);
}
}
@Test
public void testFromComplexStringWithExpiresAndHttpOnly() {
NewCookie c = NewCookie.valueOf(
"foo=bar;Comment=comment;Path=path;Max-Age=10;Domain=domain;Secure;"
+ "Expires=Wed, 09 Jun 2021 10:18:14 GMT;HttpOnly;Version=1");
assertTrue("bar".equals(c.getValue())
&& "foo".equals(c.getName()));
assertTrue(1 == c.getVersion()
&& "path".equals(c.getPath())
&& "domain".equals(c.getDomain())
&& "comment".equals(c.getComment())
&& c.isSecure()
&& c.isHttpOnly()
&& 10 == c.getMaxAge());
Date d = c.getExpiry();
assertNotNull(d);
assertEquals("Wed, 09 Jun 2021 10:18:14 GMT", HttpUtils.toHttpDate(d));
}
private Parameter createClientHeaderParameter(ClientHeaderParam anno, Class<?> clientIntf) {
Parameter p = new Parameter(ParameterType.HEADER, anno.name());
String[] values = anno.value();
String headerValue;
if (values[0] != null && values[0].length() > 2 && values[0].startsWith("{") && values[0].endsWith("}")) {
try {
headerValue = invokeBestFitComputeMethod(clientIntf, anno);
} catch (Throwable t) {
if (anno.required()) {
throwException(t);
}
return null;
}
} else {
headerValue = HttpUtils.getHeaderString(Arrays.asList(values));
}
p.setDefaultValue(headerValue);
return p;
}
/**
* Goes back
* @param fast if true then goes back to baseURI otherwise to a previous path segment
* @return updated WebClient
*/
public WebClient back(boolean fast) {
getState().setTemplates(null);
if (fast) {
getCurrentBuilder().replacePath(getBaseURI().getPath());
} else {
URI uri = getCurrentURI();
if (uri == getBaseURI()) {
return this;
}
List<PathSegment> segments = JAXRSUtils.getPathSegments(uri.getPath(), false);
getCurrentBuilder().replacePath(null);
for (int i = 0; i < segments.size() - 1; i++) {
getCurrentBuilder().path(HttpUtils.fromPathSegment(segments.get(i)));
}
}
return this;
}
private void doSetHeader(RuntimeDelegate rd, String name, Object value) {
HeaderDelegate<Object> hd = HttpUtils.getHeaderDelegate(rd, value);
if (hd != null) {
value = hd.toString(value);
}
// If value is null then all current headers of the same name should be removed
if (value == null) {
webClient.replaceHeader(name, value);
} else {
webClient.header(name, value);
}
}
private void setExchangeProperties(Message message,
Exchange exchange,
OperationResourceInfo ori,
MultivaluedMap<String, String> values,
int numberOfResources) {
final ClassResourceInfo cri = ori.getClassResourceInfo();
exchange.put(OperationResourceInfo.class, ori);
exchange.put(JAXRSUtils.ROOT_RESOURCE_CLASS, cri);
message.put(RESOURCE_METHOD, ori.getMethodToInvoke());
message.put(URITemplate.TEMPLATE_PARAMETERS, values);
String plainOperationName = ori.getMethodToInvoke().getName();
if (numberOfResources > 1) {
plainOperationName = cri.getServiceClass().getSimpleName() + "#" + plainOperationName;
}
exchange.put(RESOURCE_OPERATION_NAME, plainOperationName);
if (ori.isOneway()
|| PropertyUtils.isTrue(HttpUtils.getProtocolHeader(message, Message.ONE_WAY_REQUEST, null))) {
exchange.setOneWay(true);
}
ResourceProvider rp = cri.getResourceProvider();
if (rp instanceof SingletonResourceProvider) {
//cri.isSingleton is not guaranteed to indicate we have a 'pure' singleton
exchange.put(Message.SERVICE_OBJECT, rp.getInstance(message));
}
}
private void setResponseDate(MultivaluedMap<String, Object> headers, boolean firstTry) {
if (!firstTry || headers.containsKey(HttpHeaders.DATE)) {
return;
}
SimpleDateFormat format = HttpUtils.getHttpDateFormat();
headers.putSingle(HttpHeaders.DATE, format.format(new Date()));
}
/**
* Encoded literal characters surrounding template variables,
* ex. "a {id} b" will be encoded to "a%20{id}%20b"
* @return encoded value
*/
public String encodeLiteralCharacters(boolean isQuery) {
final float encodedRatio = 1.5f;
StringBuilder sb = new StringBuilder((int)(encodedRatio * template.length()));
for (UriChunk chunk : uriChunks) {
String val = chunk.getValue();
if (chunk instanceof Literal) {
sb.append(HttpUtils.encodePartiallyEncoded(val, isQuery));
} else {
sb.append(val);
}
}
return sb.toString();
}
public boolean isCXFResource(final HttpServletRequest request) {
try {
Application application = findApplication();
if (!applicationProvidesResources(application)) {
JAXRSServiceImpl service = (JAXRSServiceImpl)server.getEndpoint().getService();
if( service == null ) {
return false;
}
String pathToMatch = HttpUtils.getPathToMatch(request.getServletPath(), pattern, true);
final List<ClassResourceInfo> resources = service.getClassResourceInfos();
for (final ClassResourceInfo info : resources) {
if (info.getResourceClass() == null || info.getURITemplate() == null) { // possible?
continue;
}
final MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>();
if (info.getURITemplate().match(pathToMatch, parameters)) {
return true;
}
}
} else {
return true;
}
} catch (final Exception e) {
LOGGER.info("No JAX-RS service");
}
return false;
}
public void writeTo(T obj, Class<?> type, Type genType, Annotation[] anns,
MediaType mt, MultivaluedMap<String, Object> headers,
OutputStream os) throws IOException {
String encoding = HttpUtils.getSetEncoding(mt, headers, StandardCharsets.UTF_8.name());
byte[] bytes = obj.toString().getBytes(encoding);
os.write(bytes);
}
public void writeTo(T o, Class<?> clazz, Type genericType, Annotation[] annotations,
MediaType m, MultivaluedMap<String, Object> headers, OutputStream os)
throws IOException {
XMLStreamWriter writer = null;
try {
String enc = HttpUtils.getSetEncoding(m, headers, StandardCharsets.UTF_8.name());
writer = createWriter(clazz, genericType, enc, os);
writeToWriter(writer, o);
} catch (Exception ex) {
throw ExceptionUtils.toInternalServerErrorException(ex, null);
} finally {
StaxUtils.close(writer);
}
}
/**
* Retrieve map of parameters from the passed in message
*/
protected void populateMap(MultivaluedMap<String, String> params,
Annotation[] anns,
InputStream is,
MediaType mt,
boolean decode) {
if (mt.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
MultipartBody body =
AttachmentUtils.getMultipartBody(mc, attachmentDir, attachmentThreshold, attachmentMaxSize);
FormUtils.populateMapFromMultipart(params, body, PhaseInterceptorChain.getCurrentMessage(),
decode);
} else {
String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
Object servletRequest = mc != null ? mc.getHttpServletRequest() : null;
if (servletRequest == null) {
FormUtils.populateMapFromString(params,
PhaseInterceptorChain.getCurrentMessage(),
FormUtils.readBody(is, enc),
enc,
decode);
} else {
FormUtils.populateMapFromString(params,
PhaseInterceptorChain.getCurrentMessage(),
FormUtils.readBody(is, enc),
enc,
decode,
(javax.servlet.http.HttpServletRequest)servletRequest);
}
}
}
@SuppressWarnings("unchecked")
public void writeTo(T obj, Class<?> c, Type t, Annotation[] anns,
MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os)
throws IOException, WebApplicationException {
MultivaluedMap<String, String> map =
(MultivaluedMap<String, String>)(obj instanceof Form ? ((Form)obj).asMap() : obj);
boolean encoded = keepEncoded(anns);
String enc = HttpUtils.getSetEncoding(mt, headers, StandardCharsets.UTF_8.name());
FormUtils.writeMapToOutputStream(map, os, enc, encoded);
}
@Override
public MediaType getMediaType() {
if (!hasEntity()) {
return null;
}
Object mt = HttpUtils.getModifiableHeaders(m).getFirst(HttpHeaders.CONTENT_TYPE);
return mt instanceof MediaType ? (MediaType)mt : JAXRSUtils.toMediaType(mt.toString());
}
@Override
public URI buildFromEncodedMap(Map<String, ?> map) throws IllegalArgumentException,
UriBuilderException {
Map<String, String> decodedMap = new HashMap<>(map.size());
for (Map.Entry<String, ? extends Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
throw new IllegalArgumentException("Value is null");
}
String theValue = entry.getValue().toString();
if (theValue.contains("/")) {
// protecting '/' from being encoded here assumes that a given value may constitute multiple
// path segments - very questionable especially given that queries and fragments may also
// contain template vars - technically this can be covered by checking where a given template
// var is coming from and act accordingly. Confusing nonetheless.
StringBuilder buf = new StringBuilder();
String[] values = theValue.split("/");
for (int i = 0; i < values.length; i++) {
buf.append(HttpUtils.encodePartiallyEncoded(values[i], false));
if (i + 1 < values.length) {
buf.append('/');
}
}
decodedMap.put(entry.getKey(), buf.toString());
} else {
decodedMap.put(entry.getKey(), HttpUtils.encodePartiallyEncoded(theValue, false));
}
}
return doBuildFromMap(decodedMap, true, false);
}
@Override
public String toString(NewCookie value) {
if (null == value) {
throw new NullPointerException("Null cookie input");
}
StringBuilder sb = new StringBuilder();
sb.append(value.getName()).append('=').append(maybeQuoteAll(value.getValue()));
if (value.getComment() != null) {
sb.append(';').append(COMMENT).append('=').append(maybeQuoteAll(value.getComment()));
}
if (value.getDomain() != null) {
sb.append(';').append(DOMAIN).append('=').append(maybeQuoteAll(value.getDomain()));
}
if (value.getMaxAge() != -1) {
sb.append(';').append(MAX_AGE).append('=').append(value.getMaxAge());
}
if (value.getPath() != null) {
sb.append(';').append(PATH).append('=').append(maybeQuotePath(value.getPath()));
}
if (value.getExpiry() != null) {
sb.append(';').append(EXPIRES).append('=').append(HttpUtils.toHttpDate(value.getExpiry()));
}
if (value.isSecure()) {
sb.append(';').append(SECURE);
}
if (value.isHttpOnly()) {
sb.append(';').append(HTTP_ONLY);
}
sb.append(';').append(VERSION).append('=').append(value.getVersion());
return sb.toString();
}
private List<String> toListOfStrings(List<Object> values) {
if (values == null) {
return null;
}
List<String> stringValues = new ArrayList<>(values.size());
HeaderDelegate<Object> hd = HttpUtils.getHeaderDelegate(values.get(0));
for (Object value : values) {
String actualValue = hd == null ? value.toString() : hd.toString(value);
stringValues.add(actualValue);
}
return stringValues;
}
@SuppressWarnings("unchecked")
@Override
public void aroundWriteTo(WriterInterceptorContext c) throws IOException, WebApplicationException {
MultivaluedMap<String, Object> headers = c.getHeaders();
Object mtObject = headers.getFirst(HttpHeaders.CONTENT_TYPE);
MediaType entityMt = mtObject == null ? c.getMediaType() : JAXRSUtils.toMediaType(mtObject.toString());
m.put(Message.CONTENT_TYPE, entityMt.toString());
Class<?> entityCls = c.getType();
Type entityType = c.getGenericType();
Annotation[] entityAnns = c.getAnnotations();
if (writer == null
|| m.get(ProviderFactory.PROVIDER_SELECTION_PROPERTY_CHANGED) == Boolean.TRUE
&& !writer.isWriteable(entityCls, entityType, entityAnns, entityMt)) {
writer = (MessageBodyWriter<Object>)ProviderFactory.getInstance(m)
.createMessageBodyWriter(entityCls, entityType, entityAnns, entityMt, m);
}
if (writer == null) {
String errorMessage = JAXRSUtils.logMessageHandlerProblem("NO_MSG_WRITER", entityCls, entityMt);
throw new ProcessingException(errorMessage);
}
HttpUtils.convertHeaderValuesToString(headers, true);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Response EntityProvider is: " + writer.getClass().getName());
}
writer.writeTo(c.getEntity(),
c.getType(),
c.getGenericType(),
c.getAnnotations(),
entityMt,
headers,
c.getOutputStream());
}
public List<Locale> getAcceptableLanguages() {
List<String> ls = getListValues(HttpHeaders.ACCEPT_LANGUAGE);
if (ls.isEmpty()) {
return Collections.singletonList(new Locale("*"));
}
List<Locale> newLs = new ArrayList<>();
Map<Locale, Float> prefs = new HashMap<>();
for (String l : ls) {
String[] pair = l.split(";");
Locale locale = HttpUtils.getLocale(pair[0].trim());
newLs.add(locale);
if (pair.length > 1) {
String[] pair2 = pair[1].split("=");
if (pair2.length > 1) {
prefs.put(locale, JAXRSUtils.getMediaTypeQualityFactor(pair2[1].trim()));
} else {
prefs.put(locale, 1F);
}
} else {
prefs.put(locale, 1F);
}
}
if (newLs.size() <= 1) {
return newLs;
}
Collections.sort(newLs, new AcceptLanguageComparator(prefs));
return newLs;
}
private List<String> getListValues(String headerName) {
List<String> values = headers.get(headerName);
if (values == null || values.isEmpty() || values.get(0) == null) {
return Collections.emptyList();
}
if (HttpUtils.isDateRelatedHeader(headerName)) {
return values;
}
List<String> actualValues = new LinkedList<>();
for (String v : values) {
actualValues.addAll(getHeaderValues(headerName, v));
}
return actualValues;
}
public Date getDate() {
List<String> values = headers.get(HttpHeaders.DATE);
if (values == null || values.isEmpty() || StringUtils.isEmpty(values.get(0))) {
return null;
}
return HttpUtils.getHttpDate(values.get(0));
}
public int getLength() {
List<String> values = headers.get(HttpHeaders.CONTENT_LENGTH);
if (values == null || values.size() != 1) {
return -1;
}
return HttpUtils.getContentLength(values.get(0));
}
/**
* {@inheritDoc}
*/
@Override
public Client modified(Date date, boolean ifNot) {
SimpleDateFormat dateFormat = HttpUtils.getHttpDateFormat();
String hName = ifNot ? HttpHeaders.IF_UNMODIFIED_SINCE : HttpHeaders.IF_MODIFIED_SINCE;
state.getRequestHeaders().putSingle(hName, dateFormat.format(date));
return this;
}
public Date fromString(String value) {
if (value == null) {
throw new IllegalArgumentException("Date value can not be null");
}
return HttpUtils.getHttpDate(value);
}