Java Code Examples for org.apache.cxf.jaxrs.utils.HttpUtils

The following examples show how to use org.apache.cxf.jaxrs.utils.HttpUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   Source File: StringTextProvider.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source Project: cxf   Source File: RequestImpl.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 3
Source Project: cxf   Source File: RequestImpl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: cxf   Source File: UrlEncodingParamConverter.java    License: Apache License 2.0 6 votes vote down vote up
@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();

}
 
Example 5
Source Project: cxf   Source File: HttpHeadersImpl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 6
Source Project: cxf   Source File: FormEncodingProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"));

}
 
Example 7
Source Project: cxf   Source File: AegisElementProvider.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 8
Source Project: cxf   Source File: NewCookieHeaderProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 9
Source Project: cxf   Source File: MicroProfileClientProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 10
Source Project: cxf   Source File: WebClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source Project: cxf   Source File: InvocationBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 12
Source Project: cxf   Source File: JAXRSInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example 13
Source Project: cxf   Source File: JAXRSOutInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example 14
Source Project: cxf   Source File: URITemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 15
Source Project: tomee   Source File: CxfRsHttpListener.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source Project: cxf   Source File: PrimitiveTextProvider.java    License: Apache License 2.0 5 votes vote down vote up
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);

}
 
Example 17
Source Project: cxf   Source File: DataBindingProvider.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 18
Source Project: cxf   Source File: FormEncodingProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 19
Source Project: cxf   Source File: FormEncodingProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example 20
Source Project: cxf   Source File: ClientRequestContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 21
Source Project: cxf   Source File: UriBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 22
Source Project: cxf   Source File: NewCookieHeaderProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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();

}
 
Example 23
Source Project: cxf   Source File: ResponseImpl.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 24
Source Project: cxf   Source File: WriterInterceptorMBW.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 25
Source Project: cxf   Source File: HttpHeadersImpl.java    License: Apache License 2.0 5 votes vote down vote up
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;

}
 
Example 26
Source Project: cxf   Source File: HttpHeadersImpl.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Source Project: cxf   Source File: HttpHeadersImpl.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 28
Source Project: cxf   Source File: HttpHeadersImpl.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 29
Source Project: cxf   Source File: AbstractClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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;
}
 
Example 30
Source Project: cxf   Source File: DateHeaderProvider.java    License: Apache License 2.0 5 votes vote down vote up
public Date fromString(String value) {

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