javax.ws.rs.core.UriBuilderException#org.apache.cxf.jaxrs.utils.HttpUtils源码实例Demo

下面列出了javax.ws.rs.core.UriBuilderException#org.apache.cxf.jaxrs.utils.HttpUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cxf   文件: StringTextProvider.java
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);
    }
}
 
源代码2 项目: cxf   文件: RequestImpl.java
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);
}
 
源代码3 项目: cxf   文件: RequestImpl.java
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;
}
 
源代码4 项目: cxf   文件: UrlEncodingParamConverter.java
@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();

}
 
源代码5 项目: cxf   文件: HttpHeadersImpl.java
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;
}
 
源代码6 项目: cxf   文件: FormEncodingProviderTest.java
@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"));

}
 
源代码7 项目: cxf   文件: AegisElementProvider.java
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);
    }
}
 
源代码8 项目: cxf   文件: NewCookieHeaderProviderTest.java
@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));
}
 
源代码9 项目: cxf   文件: MicroProfileClientProxyImpl.java
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;
}
 
源代码10 项目: cxf   文件: WebClient.java
/**
 * 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;
}
 
源代码11 项目: cxf   文件: InvocationBuilderImpl.java
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);
    }
}
 
源代码12 项目: cxf   文件: JAXRSInInterceptor.java
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));
    }
}
 
源代码13 项目: cxf   文件: JAXRSOutInterceptor.java
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()));
}
 
源代码14 项目: cxf   文件: URITemplate.java
/**
 * 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();
}
 
源代码15 项目: tomee   文件: CxfRsHttpListener.java
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;
}
 
源代码16 项目: cxf   文件: PrimitiveTextProvider.java
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);

}
 
源代码17 项目: cxf   文件: DataBindingProvider.java
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);
    }
}
 
源代码18 项目: cxf   文件: FormEncodingProvider.java
/**
 * 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);
        }
    }
}
 
源代码19 项目: cxf   文件: FormEncodingProvider.java
@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);

}
 
源代码20 项目: cxf   文件: ClientRequestContextImpl.java
@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());
}
 
源代码21 项目: cxf   文件: UriBuilderImpl.java
@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);
}
 
源代码22 项目: cxf   文件: NewCookieHeaderProvider.java
@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();

}
 
源代码23 项目: cxf   文件: ResponseImpl.java
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;
}
 
源代码24 项目: cxf   文件: WriterInterceptorMBW.java
@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());
}
 
源代码25 项目: cxf   文件: HttpHeadersImpl.java
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;

}
 
源代码26 项目: cxf   文件: HttpHeadersImpl.java
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;
}
 
源代码27 项目: cxf   文件: HttpHeadersImpl.java
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));
}
 
源代码28 项目: cxf   文件: HttpHeadersImpl.java
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));
}
 
源代码29 项目: cxf   文件: AbstractClient.java
/**
 * {@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;
}
 
源代码30 项目: cxf   文件: DateHeaderProvider.java
public Date fromString(String value) {

        if (value == null) {
            throw new IllegalArgumentException("Date value can not be null");
        }
        return HttpUtils.getHttpDate(value);
    }