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

The following examples show how to use org.apache.cxf.jaxrs.utils.HttpUtils. 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 File: WebClient.java    From cxf with 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 #2
Source File: MicroProfileClientProxyImpl.java    From cxf with 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 #3
Source File: StringTextProvider.java    From cxf with 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 #4
Source File: RequestImpl.java    From cxf with 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 #5
Source File: RequestImpl.java    From cxf with 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 #6
Source File: FormEncodingProviderTest.java    From cxf with 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 File: UrlEncodingParamConverter.java    From cxf with 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 #8
Source File: AegisElementProvider.java    From cxf with 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 #9
Source File: HttpHeadersImpl.java    From cxf with 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 #10
Source File: NewCookieHeaderProviderTest.java    From cxf with 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 #11
Source File: FormEncodingProvider.java    From cxf with 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 #12
Source File: ClientResponseContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasEntity() {
    // Is Content-Length is explicitly set to 0 ?
    if (HttpUtils.isPayloadEmpty(getHeaders())) {
        return false;
    }
    try {
        return !IOUtils.isEmpty(getEntityStream());
    } catch (IOException ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example #13
Source File: AbstractSSOSpHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String createCookie(String name,
                              String value,
                              String path,
                              String domain) {

    String contextCookie = name + "=" + value;
    // Setting a specific path restricts the browsers
    // to return a cookie only to the web applications
    // listening on that specific context path
    if (path != null) {
        contextCookie += ";Path=" + path;
    }

    // Setting a specific domain further restricts the browsers
    // to return a cookie only to the web applications
    // listening on the specific context path within a particular domain
    if (domain != null) {
        contextCookie += ";Domain=" + domain;
    }

    if (stateTimeToLive > 0) {
        // Keep the cookie across the browser restarts until it actually expires.
        // Note that the Expires property has been deprecated but apparently is
        // supported better than 'max-age' property by different browsers
        // (Firefox, IE, etc)
        Instant expires = Instant.ofEpochMilli(System.currentTimeMillis() + stateTimeToLive);
        String cookieExpires =
            HttpUtils.getHttpDateFormat().format(Date.from(expires.atZone(ZoneOffset.UTC).toInstant()));
        contextCookie += ";Expires=" + cookieExpires;
    }

    //TODO: Consider adding an 'HttpOnly' attribute

    return contextCookie;
}
 
Example #14
Source File: PrimitiveTextProvider.java    From cxf with 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 #15
Source File: DateHeaderProvider.java    From cxf with 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);
    }
 
Example #16
Source File: AbstractClient.java    From cxf with 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 #17
Source File: ResponseImpl.java    From cxf with 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 #18
Source File: AbstractImplicitGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void finalizeResponse(StringBuilder sb, OAuthRedirectionState state) {
    if (state.getState() != null) {
        sb.append('&');
        String stateParam = state.getState();
        sb.append(OAuthConstants.STATE).append('=').append(HttpUtils.urlEncode(stateParam));
    }
    if (reportClientId) {
        sb.append('&').append(OAuthConstants.CLIENT_ID).append('=').append(state.getClientId());
    }
}
 
Example #19
Source File: AbstractImplicitGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected StringBuilder prepareRedirectResponse(OAuthRedirectionState state,
                                      Client client,
                                      List<String> requestedScope,
                                      List<String> approvedScope,
                                      UserSubject userSubject,
                                      ServerAccessToken preAuthorizedToken) {

    ClientAccessToken clientToken =
        getClientAccessToken(state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken);
    // return the token by appending it as a fragment parameter to the redirect URI

    StringBuilder sb = getUriWithFragment(state.getRedirectUri());

    sb.append(OAuthConstants.ACCESS_TOKEN).append('=').append(clientToken.getTokenKey());
    sb.append('&');
    sb.append(OAuthConstants.ACCESS_TOKEN_TYPE).append('=').append(clientToken.getTokenType());

    if (isWriteOptionalParameters()) {
        sb.append('&').append(OAuthConstants.ACCESS_TOKEN_EXPIRES_IN)
            .append('=').append(clientToken.getExpiresIn());
        if (!StringUtils.isEmpty(clientToken.getApprovedScope())) {
            sb.append('&').append(OAuthConstants.SCOPE).append('=')
                .append(HttpUtils.queryEncode(clientToken.getApprovedScope()));
        }
        for (Map.Entry<String, String> entry : clientToken.getParameters().entrySet()) {
            sb.append('&').append(entry.getKey()).append('=').append(HttpUtils.queryEncode(entry.getValue()));
        }
    }
    if (clientToken.getRefreshToken() != null) {
        processRefreshToken(sb, clientToken.getRefreshToken());
    }

    finalizeResponse(sb, state);
    return sb;
}
 
Example #20
Source File: WriterInterceptorMBW.java    From cxf with 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 #21
Source File: JAXRSOutInterceptor.java    From cxf with 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 #22
Source File: DateHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testToFromSimpleString() {
    Date retry = new Date();
    ServiceUnavailableException ex = new ServiceUnavailableException(retry);
    Date retry2 = ex.getRetryTime(new Date());
    assertEquals(HttpUtils.toHttpDate(retry), HttpUtils.toHttpDate(retry2));
}
 
Example #23
Source File: HttpHeadersImpl.java    From cxf with 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 #24
Source File: JAXRSInInterceptor.java    From cxf with 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 #25
Source File: HttpHeadersImpl.java    From cxf with 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 #26
Source File: HttpHeadersImpl.java    From cxf with 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 #27
Source File: InvocationBuilderImpl.java    From cxf with 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 #28
Source File: HttpHeadersImpl.java    From cxf with 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 File: ResponseImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void doTestDate(String dateHeader) {
    boolean date = HttpHeaders.DATE.equals(dateHeader);
    ResponseImpl ri = new ResponseImpl(200);
    MetadataMap<String, Object> meta = new MetadataMap<>();
    meta.add(dateHeader, "Tue, 21 Oct 2008 17:00:00 GMT");
    ri.addMetadata(meta);
    assertEquals(HttpUtils.getHttpDate("Tue, 21 Oct 2008 17:00:00 GMT"),
                 date ? ri.getDate() : ri.getLastModified());
}
 
Example #30
Source File: CrossOriginResourceSharingFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Method getResourceMethod(Message m, String httpMethod) {
    String requestUri = HttpUtils.getPathToMatch(m, true);

    List<ClassResourceInfo> resources = JAXRSUtils.getRootResources(m);
    Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources =
        JAXRSUtils.selectResourceClass(resources, requestUri, m);
    if (matchedResources == null) {
        return null;
    }
    MultivaluedMap<String, String> values = new MetadataMap<>();
    OperationResourceInfo ori = findPreflightMethod(matchedResources, requestUri, httpMethod, values, m);
    return ori == null ? null : ori.getAnnotatedMethod();
}