Java Code Examples for javax.ws.rs.core.HttpHeaders#getAcceptableMediaTypes()

The following examples show how to use javax.ws.rs.core.HttpHeaders#getAcceptableMediaTypes() . 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: TrellisRequest.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * Bundle together some request contexts.
 * @param request the Request object
 * @param uriInfo the URI information
 * @param headers the HTTP headers
 * @param secCtx the security context
 */
public TrellisRequest(final Request request, final UriInfo uriInfo, final HttpHeaders headers,
        final SecurityContext secCtx) {
    // Extract header values
    this.headers = headers.getRequestHeaders();
    this.acceptableMediaTypes = headers.getAcceptableMediaTypes();

    // Extract URI values
    this.parameters = uriInfo.getQueryParameters();
    this.baseUrl = buildBaseUrl(uriInfo.getBaseUri(), this.headers);
    this.path = uriInfo.getPathParameters().getFirst("path");
    this.trailingSlash = uriInfo.getPath().endsWith("/");

    // Extract request method
    this.method = request.getMethod();

    // Security context value
    this.secCtx = secCtx;
}
 
Example 2
Source File: ODataExceptionWrapper.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private ContentType getContentTypeByAcceptHeader(final HttpHeaders httpHeaders) {
  for (MediaType type : httpHeaders.getAcceptableMediaTypes()) {
    if (ContentType.isParseable(type.toString())) {
      ContentType convertedContentType = ContentType.create(type.toString());
      if (convertedContentType.isWildcard()
          || ContentType.APPLICATION_XML.equals(convertedContentType)
          || ContentType.APPLICATION_XML_CS_UTF_8.equals(convertedContentType)
          || ContentType.APPLICATION_ATOM_XML.equals(convertedContentType)
          || ContentType.APPLICATION_ATOM_XML_CS_UTF_8.equals(convertedContentType)) {
        return ContentType.APPLICATION_XML;
      } else if (ContentType.APPLICATION_JSON.equals(convertedContentType)
          || ContentType.APPLICATION_JSON_CS_UTF_8.equals(convertedContentType)
          || ContentType.APPLICATION_JSON_ODATA_VERBOSE.equals(convertedContentType)) {
        return ContentType.APPLICATION_JSON;
      }
    }
  }
  return ContentType.APPLICATION_XML;
}
 
Example 3
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMediaTypes() throws Exception {

    Message m = createMessage(createHeaders());
    HttpHeaders h = new HttpHeadersImpl(m);
    List<MediaType> acceptValues = h.getAcceptableMediaTypes();
    assertEquals(3, acceptValues.size());
    assertEquals("text/*;q=1", acceptValues.get(0).toString());
    assertEquals("application/xml", acceptValues.get(1).toString());
    assertEquals("text/bar;q=0.6", acceptValues.get(2).toString());
}
 
Example 4
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNoMediaTypes() throws Exception {

    Message m = new MessageImpl();
    m.put(Message.PROTOCOL_HEADERS, Collections.emptyMap());
    HttpHeaders h = new HttpHeadersImpl(m);
    List<MediaType> acceptValues = h.getAcceptableMediaTypes();
    assertEquals(1, acceptValues.size());
    assertEquals("*/*", acceptValues.get(0).toString());
}
 
Example 5
Source File: MediaTypeMatcher.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean isHtmlRequest(HttpHeaders headers) {
    for (javax.ws.rs.core.MediaType m : headers.getAcceptableMediaTypes()) {
        if (!m.isWildcardType() && m.isCompatible(javax.ws.rs.core.MediaType.TEXT_HTML_TYPE)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: ODataExceptionWrapper.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
private ContentType getContentTypeByAcceptHeader(final HttpHeaders httpHeaders) {
  for (MediaType type : httpHeaders.getAcceptableMediaTypes()) {
    if (ContentType.isParseable(type.toString())) {
      ContentType convertedContentType = ContentType.create(type.toString());
      if (convertedContentType.isWildcard()
          || ContentType.APPLICATION_XML.equals(convertedContentType) || ContentType.APPLICATION_XML_CS_UTF_8.equals(convertedContentType)
          || ContentType.APPLICATION_ATOM_XML.equals(convertedContentType) || ContentType.APPLICATION_ATOM_XML_CS_UTF_8.equals(convertedContentType)) {
        return ContentType.APPLICATION_XML;
      } else if (ContentType.APPLICATION_JSON.equals(convertedContentType) || ContentType.APPLICATION_JSON_CS_UTF_8.equals(convertedContentType)) {
        return ContentType.APPLICATION_JSON;
      }
    }
  }
  return ContentType.APPLICATION_XML;
}
 
Example 7
Source File: JAASAuthenticationFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected boolean isRedirectPossible(HttpHeaders headers) {
    List<MediaType> clientTypes = headers.getAcceptableMediaTypes();
    return !JAXRSUtils.intersectMimeTypes(clientTypes, HTML_MEDIA_TYPES, false)
                      .isEmpty();
}
 
Example 8
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void doFilter(ContainerRequestContext context, Message m) {
    if (!"GET".equals(m.get(Message.HTTP_REQUEST_METHOD))) {
        return;
    }

    UriInfo ui = context.getUriInfo();
    if (!ui.getQueryParameters().containsKey(WADL_QUERY)) {
        if (stylesheetReference != null || !docLocationMap.isEmpty()) {
            String path = ui.getPath(false);
            if (path.startsWith("/") && path.length() > 0) {
                path = path.substring(1);
            }
            if (stylesheetReference != null && path.endsWith(".xsl")
                || docLocationMap.containsKey(path)) {
                context.abortWith(getExistingResource(m, ui, path));
            }
        }
        return;
    }

    if (ignoreRequests) {
        context.abortWith(Response.status(404).build());
        return;
    }

    if (whiteList != null && !whiteList.isEmpty()) {
        ServletRequest servletRequest = (ServletRequest)m.getContextualProperty(
            "HTTP.REQUEST");
        String remoteAddress = null;
        if (servletRequest != null) {
            remoteAddress = servletRequest.getRemoteAddr();
        } else {
            remoteAddress = "";
        }
        boolean foundMatch = false;
        for (String addr : whiteList) {
            if (addr.equals(remoteAddress)) {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch) {
            context.abortWith(Response.status(404).build());
            return;
        }
    }

    HttpHeaders headers = new HttpHeadersImpl(m);
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    MediaType type = accepts.contains(WADL_TYPE) ? WADL_TYPE : accepts
        .contains(MediaType.APPLICATION_JSON_TYPE) ? MediaType.APPLICATION_JSON_TYPE
            : defaultWadlResponseMediaType;

    Response response = getExistingWadl(m, ui, type);
    if (response != null) {
        context.abortWith(response);
        return;
    }

    boolean isJson = isJson(type);

    StringBuilder sbMain = generateWADL(getBaseURI(m, ui), getResourcesList(m, ui), isJson, m, ui);

    m.getExchange().put(JAXRSUtils.IGNORE_MESSAGE_WRITERS, !isJson && ignoreMessageWriters);
    Response r = Response.ok().type(type).entity(createResponseEntity(m, ui, sbMain.toString(), isJson)).build();
    context.abortWith(r);
}
 
Example 9
Source File: AccountLoader.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Object getAccountService(KeycloakSession session, EventBuilder event) {
    RealmModel realm = session.getContext().getRealm();

    ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    if (client == null || !client.isEnabled()) {
        logger.debug("account management not enabled");
        throw new NotFoundException("account management not enabled");
    }

    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    HttpHeaders headers = session.getContext().getRequestHeaders();
    MediaType content = headers.getMediaType();
    List<MediaType> accepts = headers.getAcceptableMediaTypes();

    Theme theme = getTheme(session);
    boolean deprecatedAccount = isDeprecatedFormsAccountConsole(theme);
    UriInfo uriInfo = session.getContext().getUri();

    if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
        return new CorsPreflightService(request);
    } else if ((accepts.contains(MediaType.APPLICATION_JSON_TYPE) || MediaType.APPLICATION_JSON_TYPE.equals(content)) && !uriInfo.getPath().endsWith("keycloak.json")) {
        AuthenticationManager.AuthResult authResult = new AppAuthManager().authenticateBearerToken(session);
        if (authResult == null) {
            throw new NotAuthorizedException("Bearer token required");
        }

        if (authResult.getUser().getServiceAccountClientLink() != null) {
            throw new NotAuthorizedException("Service accounts are not allowed to access this service");
        }

        Auth auth = new Auth(session.getContext().getRealm(), authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false);
        AccountRestService accountRestService = new AccountRestService(session, auth, client, event);
        ResteasyProviderFactory.getInstance().injectProperties(accountRestService);
        accountRestService.init();
        return accountRestService;
    } else {
        if (deprecatedAccount) {
            AccountFormService accountFormService = new AccountFormService(realm, client, event);
            ResteasyProviderFactory.getInstance().injectProperties(accountFormService);
            accountFormService.init();
            return accountFormService;
        } else {
            AccountConsole console = new AccountConsole(realm, client, theme);
            ResteasyProviderFactory.getInstance().injectProperties(console);
            console.init();
            return console;
        }
    }
}