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

The following examples show how to use javax.ws.rs.core.HttpHeaders#getRequestHeader() . 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: HttpHeadersImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHeader() throws Exception {

    Message m = createMessage(createHeaders());
    m.put(HttpHeadersImpl.HEADER_SPLIT_PROPERTY, "true");
    HttpHeaders h = new HttpHeadersImpl(m);
    List<String> acceptValues = h.getRequestHeader("Accept");
    assertEquals(3, acceptValues.size());
    assertEquals("text/bar;q=0.6", acceptValues.get(0));
    assertEquals("text/*;q=1", acceptValues.get(1));
    assertEquals("application/xml", acceptValues.get(2));
    List<String> contentValues = h.getRequestHeader("Content-Type");
    assertEquals(1, contentValues.size());
    assertEquals("*/*", contentValues.get(0));

    List<String> dateValues = h.getRequestHeader("Date");
    assertEquals(1, dateValues.size());
    assertEquals("Tue, 21 Oct 2008 17:00:00 GMT", dateValues.get(0));
}
 
Example 2
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHeaderWithQuotes1() throws Exception {

    MetadataMap<String, String> headers = createHeader("COMPLEX_HEADER",
        "a1=\"a\", a2=\"a\";param, b, b;param, c1=\"c, d, e\", "
        + "c2=\"c, d, e\";param, a=b, a=b;p=p1, a2=\"a\";param=p,"
        + "a3=\"a\";param=\"p,b\"");
    Message m = createMessage(headers);
    m.put(HttpHeadersImpl.HEADER_SPLIT_PROPERTY, "true");

    HttpHeaders h = new HttpHeadersImpl(m);
    List<String> values = h.getRequestHeader("COMPLEX_HEADER");
    assertNotNull(values);
    assertEquals(10, values.size());
    assertEquals("a1=\"a\"", values.get(0));
    assertEquals("a2=\"a\";param", values.get(1));
    assertEquals("b", values.get(2));
    assertEquals("b;param", values.get(3));
    assertEquals("c1=\"c, d, e\"", values.get(4));
    assertEquals("c2=\"c, d, e\";param", values.get(5));
    assertEquals("a=b", values.get(6));
    assertEquals("a=b;p=p1", values.get(7));
    assertEquals("a2=\"a\";param=p", values.get(8));
    assertEquals("a3=\"a\";param=\"p,b\"", values.get(9));
}
 
Example 3
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHeaderWithQuotes2() throws Exception {

    MetadataMap<String, String> headers =
        createHeader("X-WSSE", "UsernameToken Username=\"Foo\", Nonce=\"bar\"");
    Message m = createMessage(headers);
    m.put(HttpHeadersImpl.HEADER_SPLIT_PROPERTY, "true");

    HttpHeaders h = new HttpHeadersImpl(m);
    List<String> values = h.getRequestHeader("X-WSSE");
    assertNotNull(values);
    assertEquals(3, values.size());
    assertEquals("UsernameToken", values.get(0));
    assertEquals("Username=\"Foo\"", values.get(1));
    assertEquals("Nonce=\"bar\"", values.get(2));
}
 
Example 4
Source File: RequestPreprocessor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void handleMethod(Message m,
                          MultivaluedMap<String, String> queries,
                          HttpHeaders headers) {
    if (MessageUtils.getContextualBoolean(m, ALLOW_HTTP_METHOD_OVERRIDE, false)) {
        String method = queries.getFirst(METHOD_QUERY);
        if (method == null) {
            List<String> list = headers.getRequestHeader(METHOD_HEADER);
            if (list != null && list.size() == 1) {
                method = list.get(0);
            }
        }
        if (method != null) {
            m.put(Message.HTTP_REQUEST_METHOD, method);
        }
    }
}
 
Example 5
Source File: SitemapResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/{sitemapname: [a-zA-Z_0-9]+}/{pageid: [a-zA-Z_0-9]+}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Polls the data for a sitemap.", response = PageDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 404, message = "Sitemap with requested name does not exist or page does not exist, or page refers to a non-linkable widget"),
        @ApiResponse(code = 400, message = "Invalid subscription id has been provided.") })
public Response getPageData(@Context HttpHeaders headers,
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
        @PathParam("pageid") @ApiParam(value = "page id") String pageId,
        @QueryParam("subscriptionid") @ApiParam(value = "subscriptionid") @Nullable String subscriptionId,
        @QueryParam("includeHidden") @ApiParam(value = "include hidden widgets") boolean includeHiddenWidgets) {
    final Locale locale = localeService.getLocale(language);
    logger.debug("Received HTTP GET request from IP {} at '{}'", request.getRemoteAddr(), uriInfo.getPath());

    if (subscriptionId != null) {
        try {
            subscriptions.setPageId(subscriptionId, sitemapname, pageId);
        } catch (IllegalArgumentException e) {
            return JSONResponse.createErrorResponse(Response.Status.BAD_REQUEST, e.getMessage());
        }
    }

    boolean timeout = false;
    if (headers.getRequestHeader("X-Atmosphere-Transport") != null) {
        // Make the REST-API pseudo-compatible with openHAB 1.x
        // The client asks Atmosphere for server push functionality,
        // so we do a simply listening for changes on the appropriate items
        // The blocking has a timeout of 30 seconds. If this timeout is reached,
        // we notice this information in the response object.
        timeout = blockUnlessChangeOccurs(sitemapname, pageId);
    }
    PageDTO responseObject = getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build(), locale, timeout,
            includeHiddenWidgets);
    return Response.ok(responseObject).build();
}
 
Example 6
Source File: Pendenze.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
@POST
@Path("/{idA2A}/{idPendenza}")
@Consumes({ "application/json" })
public Response updatePendenza(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @PathParam("idA2A") String idA2A, @PathParam("idPendenza") String idPendenza, java.io.InputStream is, @QueryParam("stampaAvviso") @DefaultValue(value="false") Boolean stampaAvviso, @QueryParam(value="avvisaturaDigitale") @DefaultValue(value="false")  Boolean avvisaturaDigitale, @QueryParam("modalitaAvvisaturaDigitale") @DefaultValue(value="ASINCRONA") ModalitaAvvisaturaDigitale modalitaAvvisaturaDigitale){
    this.buildContext();
    if(httpHeaders.getRequestHeader("X-HTTP-Method-Override") != null && !httpHeaders.getRequestHeader("X-HTTP-Method-Override").isEmpty() && httpHeaders.getRequestHeader("X-HTTP-Method-Override").get(0).equals("PATCH"))
    	return this.controller.pendenzeIdA2AIdPendenzaPATCH(this.getUser(), uriInfo, httpHeaders,  idA2A,  idPendenza, is);
    if(httpHeaders.getRequestHeader("X-HTTP-Method-Override") != null && !httpHeaders.getRequestHeader("X-HTTP-Method-Override").isEmpty() && httpHeaders.getRequestHeader("X-HTTP-Method-Override").get(0).equals("PUT"))
        return this.controller.pendenzeIdA2AIdPendenzaPUT(this.getUser(), uriInfo, httpHeaders,  idA2A,  idPendenza, is, stampaAvviso, avvisaturaDigitale, modalitaAvvisaturaDigitale);
 
    String transactionId = this.getContext().getTransactionId();
    return this.controller.handleEventoFail(Response.status(405), transactionId, null, "Operazione non consentita").build();
}
 
Example 7
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String[] getUsernameAndPassword(final HttpHeaders httpHeaders) {
    final List<String> authHeaders = httpHeaders.getRequestHeader(HttpHeaders.AUTHORIZATION);

    if (authHeaders == null || authHeaders.size() == 0) {
        return null;
    }

    String credentials = null;

    for (final String authHeader : authHeaders) {
        if (authHeader.startsWith(BASIC_PREFIX)) {
            final String[] split = authHeader.trim().split("\\s+");

            if (split.length != 2) return null;

            credentials = split[1];
        }
    }

    try {
        String val = new String(Base64.decode(credentials));
        int seperatorIndex = val.indexOf(":");
        if(seperatorIndex == -1) return new String[]{val};
        String user = val.substring(0, seperatorIndex);
        String pw = val.substring(seperatorIndex + 1);
        return new String[]{user,pw};
    } catch (final IOException e) {
        throw new RuntimeException("Failed to parse credentials.", e);
    }
}
 
Example 8
Source File: Rpp.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
@POST
@Path("/{idDominio}/{iuv}/n/a")
@Consumes({ "application/json" })
public Response updateRppPOST(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, java.io.InputStream is, @PathParam("idDominio") String idDominio, @PathParam("iuv") String iuv){
    this.buildContext();
    if(httpHeaders.getRequestHeader("X-HTTP-Method-Override") != null && !httpHeaders.getRequestHeader("X-HTTP-Method-Override").isEmpty() && httpHeaders.getRequestHeader("X-HTTP-Method-Override").get(0).equals("PATCH"))
    	return this.controller.updateRpp(this.getUser(), uriInfo, httpHeaders, is,  idDominio,  iuv,  "n/a");
  
    String transactionId = this.getContext().getTransactionId();
    return this.controller.handleEventoFail(Response.status(405), transactionId, null, "Operazione non consentita").build();
}
 
Example 9
Source File: HttpHeadersMethodsResource.java    From tomee with Apache License 2.0 5 votes vote down vote up
@GET
public String getHeader(@Context HttpHeaders headers, @QueryParam("name") String headerName) {
    try {
        List<String> values = headers.getRequestHeader(headerName);
        if (values == null) {
            return "requestheader:null:";
        } else {
            values = new ArrayList<String>(values);
        }
        Collections.sort(values);
        return "requestheader:" + values.toString();
    } catch (IllegalArgumentException e) {
        return "requestheader:illegalarg:";
    }
}
 
Example 10
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEmptyHeader() throws Exception {

    Message m = new MessageImpl();
    // this is what happens at runtime and is tested in the system tests
    Map<String, List<String>> headers =
        new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    headers.put("A", Collections.<String>emptyList());
    m.put(Message.PROTOCOL_HEADERS, headers);
    HttpHeaders h = new HttpHeadersImpl(m);
    List<String> values = h.getRequestHeader("A");
    assertTrue(values.isEmpty());
}
 
Example 11
Source File: AbstractAuthenticationAuthorizationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    HttpHeaders headers = new HttpHeadersImpl(message);
    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (log.isDebugEnabled()) {
        log.debug("Executing " + this.getClass());
    }
    if (!AuthenticationContext.isAthenticated() && authHeader != null && authHeader.size() > 0 &&
            canHandle(authHeader.get(0).trim().split(" ")[0])) {
        return handle(message, classResourceInfo);
    }
    // give the control to the next handler
    return null;
}
 
Example 12
Source File: SchemaRegistryResource.java    From registry with Apache License 2.0 5 votes vote down vote up
private boolean isThrowErrorIfExists(HttpHeaders httpHeaders) {
    List<String> values = httpHeaders.getRequestHeader(THROW_ERROR_IF_EXISTS);
    if (values != null) {
        values = httpHeaders.getRequestHeader(THROW_ERROR_IF_EXISTS_LOWER_CASE);
    }
    return values != null && !values.isEmpty() && Boolean.parseBoolean(values.get(0));
}
 
Example 13
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHeader2() throws Exception {

    Message m = createMessage(createHeaders());
    HttpHeaders h = new HttpHeadersImpl(m);

    List<String> values = h.getRequestHeader("a");
    assertEquals(2, values.size());
    assertEquals("1", values.get(0));
    assertEquals("2", values.get(1));
}
 
Example 14
Source File: HttpHeadersImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHeaderNameValue() throws Exception {

    Message m = createMessage(createHeader("COMPLEX_HEADER",  "b=c; param=c, a=b;param=b"));
    m.put(HttpHeadersImpl.HEADER_SPLIT_PROPERTY, "true");

    HttpHeaders h = new HttpHeadersImpl(m);
    List<String> values = h.getRequestHeader("COMPLEX_HEADER");
    assertNotNull(values);
    assertEquals(2, values.size());
    assertEquals("b=c; param=c", values.get(0));
    assertEquals("a=b;param=b", values.get(1));
}
 
Example 15
Source File: ResteasyContextLocaleResolver.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Optional<List<LanguageRange>> getAcceptableLanguages() {
    HttpHeaders httpHeaders = ResteasyContext.getContextData(HttpHeaders.class);
    if (httpHeaders != null) {
        List<String> acceptLanguageList = httpHeaders.getRequestHeader("Accept-Language");
        if (acceptLanguageList != null && !acceptLanguageList.isEmpty()) {
            return Optional.of(LanguageRange.parse(acceptLanguageList.get(0)));
        }
    }

    return Optional.empty();
}
 
Example 16
Source File: AlbumService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void printAuthHeaders(HttpHeaders headers) {
    log.debug("-----------------Authorization headers--------------------------");
    for (String authHeader : headers.getRequestHeader(HttpHeaders.AUTHORIZATION)) {
        log.debug(authHeader);
    }
}
 
Example 17
Source File: ODataBatchResource.java    From io with Apache License 2.0 4 votes vote down vote up
/**
 * バッチリクエストを処理する.
 * @param uriInfo uriInfo
 * @param headers headers
 * @param request request
 * @param reader reader
 * @return レスポンス
 */
@POST
public Response batchRequest(
        @Context UriInfo uriInfo,
        @Context HttpHeaders headers,
        @Context Request request,
        Reader reader) {

    long startTime = System.currentTimeMillis();
    // タイムアウト時間 (dc_config.properties com.fujitsu.dc.core.odata.batch.timeoutInSecで設定. 単位は秒)
    long batchTimeoutInSec = DcCoreConfig.getOdataBatchRequestTimeoutInMillis();

    // Lockを他プロセスに譲るためにスリープするか否かの拡張ヘッダの値を取得する
    BatchPriority priority = BatchPriority.LOW;
    List<String> priorityHeaders = headers.getRequestHeader(X_DC_PRIORITY);
    if (priorityHeaders != null) {
        priority = BatchPriority.fromString(priorityHeaders.get(0));
    }

    timer = new BatchElapsedTimer(startTime, batchTimeoutInSec, priority);

    checkAccessContext(this.odataResource.getAccessContext());

    // TODO 不正なコンテントタイプが指定された場合エラーを返却する
    String boundary = headers.getMediaType().getParameters().get("boundary");

    // リクエストボディのパース
    BatchBodyParser parser = new BatchBodyParser();
    List<BatchBodyPart> bodyParts = parser.parse(boundary, reader, uriInfo.getRequestUri().toString());
    if (bodyParts == null || bodyParts.size() == 0) {
        // パース処理失敗
        throw DcCoreException.OData.BATCH_BODY_PARSE_ERROR;
    }
    if (bodyParts.size() > Integer.parseInt(DcCoreConfig.getOdataBatchBulkRequestMaxSize())) {
        // $Batchで指定されたリクエスト数が不正
        throw DcCoreException.OData.TOO_MANY_REQUESTS.params(bodyParts.size());
    }

    UserDataODataProducer producer = (UserDataODataProducer) this.odataResource.getODataProducer();
    entityTypeIds = producer.getEntityTypeIds();

    List<NavigationPropertyBulkContext> npBulkContexts = new ArrayList<NavigationPropertyBulkContext>();

    StringBuilder responseBody = new StringBuilder();

    // 1件ずつリクエストを実行
    for (BatchBodyPart bodyPart : bodyParts) {
        executePartRequest(responseBody, uriInfo, boundary, npBulkContexts, bodyPart);
    }

    // POSTのbulk実行
    checkAndExecBulk(responseBody, uriInfo, boundary, npBulkContexts);

    // バウンダリ終端文字列
    responseBody.append("--" + boundary + "--");

    // レスポンス作成
    String contentType = ODataBatchProvider.MULTIPART_MIXED + "; boundary=" + boundary;
    return Response.status(HttpStatus.SC_ACCEPTED)
            .header(HttpHeaders.CONTENT_TYPE, contentType)
            .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataVersion.V2.asString)
            .entity(responseBody.toString())
            .build();
}
 
Example 18
Source File: RowResource.java    From hbase with Apache License 2.0 4 votes vote down vote up
Response updateBinary(final byte[] message, final HttpHeaders headers,
    final boolean replace) {
  servlet.getMetrics().incrementRequests(1);
  if (servlet.isReadOnly()) {
    servlet.getMetrics().incrementFailedPutRequests(1);
    return Response.status(Response.Status.FORBIDDEN)
      .type(MIMETYPE_TEXT).entity("Forbidden" + CRLF)
      .build();
  }
  Table table = null;
  try {
    byte[] row = rowspec.getRow();
    byte[][] columns = rowspec.getColumns();
    byte[] column = null;
    if (columns != null) {
      column = columns[0];
    }
    long timestamp = HConstants.LATEST_TIMESTAMP;
    List<String> vals = headers.getRequestHeader("X-Row");
    if (vals != null && !vals.isEmpty()) {
      row = Bytes.toBytes(vals.get(0));
    }
    vals = headers.getRequestHeader("X-Column");
    if (vals != null && !vals.isEmpty()) {
      column = Bytes.toBytes(vals.get(0));
    }
    vals = headers.getRequestHeader("X-Timestamp");
    if (vals != null && !vals.isEmpty()) {
      timestamp = Long.parseLong(vals.get(0));
    }
    if (column == null) {
      servlet.getMetrics().incrementFailedPutRequests(1);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MIMETYPE_TEXT).entity("Bad request: Column found to be null." + CRLF)
          .build();
    }
    Put put = new Put(row);
    byte parts[][] = CellUtil.parseColumn(column);
    if (parts.length != 2) {
      return Response.status(Response.Status.BAD_REQUEST)
        .type(MIMETYPE_TEXT).entity("Bad request" + CRLF)
        .build();
    }
    put.add(CellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
      .setRow(put.getRow())
      .setFamily(parts[0])
      .setQualifier(parts[1])
      .setTimestamp(timestamp)
      .setType(Type.Put)
      .setValue(message)
      .build());
    table = servlet.getTable(tableResource.getName());
    table.put(put);
    if (LOG.isTraceEnabled()) {
      LOG.trace("PUT " + put.toString());
    }
    servlet.getMetrics().incrementSucessfulPutRequests(1);
    return Response.ok().build();
  } catch (Exception e) {
    servlet.getMetrics().incrementFailedPutRequests(1);
    return processException(e);
  } finally {
    if (table != null) try {
      table.close();
    } catch (IOException ioe) {
      LOG.debug("Exception received while closing the table", ioe);
    }
  }
}
 
Example 19
Source File: MicroGatewayRestAPI.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This is the service which is used to upload the usage data file.
 *
 * @param uploadedInputStream uploadedInputStream input stream from the REST request
 * @param httpHeaders         HTTP headers for the authentication mechanism
 * @return response for the Upload process
 */
@POST
@Path("/usage/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(@Multipart("file") InputStream uploadedInputStream, @Context HttpHeaders httpHeaders) {

    String uploadedFileName = null;
    String tenantDomain = null;
    String tenantAwareUsername = null;
    try {
        AuthDTO authDTO = AuthenticatorUtil.authorizeUser(httpHeaders);

        //Process continues only if the user is authorized
        if (authDTO.isAuthenticated()) {

            tenantDomain = authDTO.getTenantDomain();
            tenantAwareUsername = authDTO.getUsername();

            List<String> fileNameHeader = httpHeaders.getRequestHeader(UploadServiceConstants.FILE_NAME_HEADER);

            //If no File Name, stop the process
            if (fileNameHeader == null || fileNameHeader.isEmpty()) {
                return Response.status(Response.Status.BAD_REQUEST).entity("FileName Header is missing.\n").build();
            }
            uploadedFileName = fileNameHeader.get(0);

            if (!uploadedFileName.matches(UploadServiceConstants.FILE_NAME_REGEX)) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .entity("FileName Header is in incorrect format.\n").build();
            }
            //Add the uploaded file info into the database
            long timeStamp = Long.parseLong(uploadedFileName.split("\\.")[2]);
            UploadedFileInfoDTO dto = new UploadedFileInfoDTO(tenantDomain, uploadedFileName, timeStamp);
            UploadedUsageFileInfoDAO.persistFileUpload(dto, uploadedInputStream);
            log.info("Successfully uploaded the API Usage file [" + uploadedFileName + "] for Tenant : "
                    + tenantDomain + " By : " + tenantAwareUsername);
            return Response.status(Response.Status.CREATED).entity("File uploaded successfully.\n").build();
        } else {
            log.warn("Un Authorized access for API Usage Upload Service. " + authDTO.getMessage());
            return UploadServiceUtil.getJsonResponse(authDTO.getResponseStatus(), authDTO.getMessage(),
                    authDTO.getDescription());
        }
    } catch (UsagePublisherException | AuthenticationException e) {
        String msg = "Error occurred while uploading API Usage file : " + uploadedFileName
                + " for tenant : " + tenantDomain;
        log.error(msg, e);
        return Response.serverError().entity("Error occurred while uploading usage file. "
                + e.getMessage()).build();
    }
}
 
Example 20
Source File: JAASAuthenticationFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Response handleAuthenticationException(SecurityException ex, Message m) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    if (redirectURI != null && isRedirectPossible(headers)) {

        URI finalRedirectURI = null;

        if (!redirectURI.isAbsolute()) {
            String endpointAddress = HttpUtils.getEndpointAddress(m);
            Object basePathProperty = m.get(Message.BASE_PATH);
            if (ignoreBasePath && basePathProperty != null && !"/".equals(basePathProperty)) {
                int index = endpointAddress.lastIndexOf(basePathProperty.toString());
                if (index != -1) {
                    endpointAddress = endpointAddress.substring(0, index);
                }
            }
            finalRedirectURI = UriBuilder.fromUri(endpointAddress).path(redirectURI.toString()).build();
        } else {
            finalRedirectURI = redirectURI;
        }

        return Response.status(getRedirectStatus()).
                header(HttpHeaders.LOCATION, finalRedirectURI).build();
    }
    ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED);

    StringBuilder sb = new StringBuilder();

    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && !authHeader.isEmpty()) {
        // should HttpHeadersImpl do it ?
        String[] authValues = authHeader.get(0).split(" ");
        if (authValues.length > 0) {
            sb.append(authValues[0]);
        }
    } else {
        sb.append("Basic");
    }
    if (realmName != null) {
        sb.append(" realm=\"").append(realmName).append('"');
    }
    builder.header(HttpHeaders.WWW_AUTHENTICATE, sb.toString());

    return builder.build();
}