Java Code Examples for javax.ws.rs.core.MultivaluedMap#put()

The following examples show how to use javax.ws.rs.core.MultivaluedMap#put() . 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: CorsFilterTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void setupRequestContext(String methodValue, String originValue, final String requestMethodValue,
        String requestHeadersValue) {
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    if (originValue != null) {
        headers.put(ORIGIN_HEADER, singletonList(originValue));
    }
    if (requestMethodValue != null) {
        headers.put(ACCESS_CONTROL_REQUEST_METHOD, singletonList(requestMethodValue));
    }
    if (requestHeadersValue != null) {
        headers.put(ACCESS_CONTROL_REQUEST_HEADERS, singletonList(requestHeadersValue));
    }

    when(requestContext.getHeaders()).thenReturn(headers);
    when(requestContext.getMethod()).thenReturn(methodValue);
}
 
Example 2
Source File: OAuth2ConfigBean.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private Entity generateRequestEntity() throws IOException, StageException {
  MultivaluedMap<String, String> requestValues = new MultivaluedHashMap<>();
 switch (credentialsGrantType) {
    case CLIENT_CREDENTIALS:
      insertClientCredentialsFields(requestValues);
      break;
    case RESOURCE_OWNER:
      insertResourceOwnerFields(requestValues);
      break;
   case JWT:
     insertJWTFields(requestValues);
     break;
    default:
  }
  for (BodyKeyValueBean additionalValue : additionalValues) {
    requestValues.put(additionalValue.key, Collections.singletonList(additionalValue.value.get()));
  }
  return Entity.form(requestValues);
}
 
Example 3
Source File: ReplaceES419LanguageFilter.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
  MultivaluedMap<String, String> headers = request.getHeaders();
  if (headers.containsKey(HttpHeaders.ACCEPT_LANGUAGE)) {
    List<String> acceptLanguageValues = headers.remove(HttpHeaders.ACCEPT_LANGUAGE);

    for (int i = 0; i < acceptLanguageValues.size(); i++) {
      final String acceptLanguageValue = acceptLanguageValues.get(i);

      // replace es-419 (invalid) with es_ES (valid, hopefully good enough.)
      if (acceptLanguageValue.contains(ES_419)) {
        acceptLanguageValues.set(i, acceptLanguageValue.replace(ES_419, ES_ES));
      }
    }

    headers.put(HttpHeaders.ACCEPT_LANGUAGE, acceptLanguageValues);
  }
}
 
Example 4
Source File: ParaClient.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for objects that have properties matching some given values. A terms query.
 * @param <P> type of the object
 * @param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()}
 * @param terms a map of fields (property names) to terms (property values)
 * @param matchAll match all terms. If true - AND search, if false - OR search
 * @param pager a {@link com.erudika.para.utils.Pager}
 * @return a list of objects found
 */
public <P extends ParaObject> List<P> findTerms(String type, Map<String, ?> terms, boolean matchAll,
		Pager... pager) {
	if (terms == null) {
		return Collections.emptyList();
	}
	MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
	params.putSingle("matchall", Boolean.toString(matchAll));
	LinkedList<String> list = new LinkedList<>();
	for (Map.Entry<String, ? extends Object> term : terms.entrySet()) {
		String key = term.getKey();
		Object value = term.getValue();
		if (value != null) {
			list.add(key.concat(Config.SEPARATOR).concat(value.toString()));
		}
	}
	if (!terms.isEmpty()) {
		params.put("terms", list);
	}
	params.putSingle(Config._TYPE, type);
	params.putAll(pagerToParams(pager));
	return getItems(find("terms", params), pager);
}
 
Example 5
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates any EL expressions in the headers section of the stage configuration.
 *
 * @param record current record in context for EL evaluation
 * @return Map of headers that can be added to the Jersey Client request
 * @throws StageException if an expression could not be evaluated
 */
public MultivaluedMap<String, Object> resolveHeaders(
    Map<String, String> headers,
    Record record
) throws StageException {
  RecordEL.setRecordInContext(headerVars, record);

  MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<>();
  for (Map.Entry<String, String> entry : headers.entrySet()) {
    List<Object> header = new ArrayList<>(1);
    Object resolvedValue = headerEval.eval(headerVars, entry.getValue(), String.class);
    header.add(resolvedValue);
    requestHeaders.put(entry.getKey(), header);
  }

  return requestHeaders;
}
 
Example 6
Source File: RestJobTest.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultivaluedHeader() throws JobExecutionException {
    String goodUrl = "GOOD URL";
    when(client.resource(goodUrl)).thenReturn(webResource);

    //Create Properties
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(RestSource.CONF_URL, goodUrl);
    properties.put(RestSource.CONF_HEADERS, "{}");
    properties.put(RestSource.CONF_METHOD, "GET");
    when(response.getEntity(String.class)).thenReturn("XXXXX");

    //Return headers
    MultivaluedMap<String, String> responseHeaders = new MultivaluedMapImpl();
    responseHeaders.put("GOODHEADER", Arrays.asList("aa", "bb"));
    restSourceHandler = initDefaultHandler();
    urlHandler = new DefaultUrlHandler();
    when(schedulerContext.get("urlHandler")).thenReturn(urlHandler);
    when(response.getHeaders()).thenReturn(responseHeaders);
    when(schedulerContext.get("properties")).thenReturn(properties);
    when(schedulerContext.get("restSourceHandler")).thenReturn(restSourceHandler);

    job.execute(context);

    assertEquals(queue.size(), 1);
    assertEquals(queue.poll().getHeaders().get("GOODHEADER"), "aa, bb");
}
 
Example 7
Source File: ProxyFilterTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void setupContextHeaders(String protoHeader, String hostHeader) {
    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    if (protoHeader != null) {
        headers.put(PROTO_PROXY_HEADER, Collections.singletonList(protoHeader));
    }
    if (hostHeader != null) {
        headers.put(HOST_PROXY_HEADER, Collections.singletonList(hostHeader));
    }
    when(context.getHeaders()).thenReturn(headers);
}
 
Example 8
Source File: OAuth2TestUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public OAuth2ConfigBean setup(Client client, WebTarget target, Invocation.Builder builder, Response response, OAuth2GrantTypes grantType) {
  OAuth2ConfigBean configBean = new OAuth2ConfigBean();
  MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
  RequestEntityProcessing transferEncoding = RequestEntityProcessing.BUFFERED;
  if (grantType == OAuth2GrantTypes.CLIENT_CREDENTIALS) {
    params.put(OAuth2ConfigBean.CLIENT_ID_KEY, Collections.singletonList(clientId));
    params.put(OAuth2ConfigBean.CLIENT_SECRET_KEY, Collections.singletonList(clientSecret));
    params.put(OAuth2ConfigBean.GRANT_TYPE_KEY, Collections.singletonList(OAuth2ConfigBean.CLIENT_CREDENTIALS_GRANT));
    configBean.clientId = () -> clientId;
    configBean.clientSecret = () -> clientSecret;
  } else {
    params.put(OAuth2ConfigBean.RESOURCE_OWNER_KEY, Collections.singletonList(clientId));
    params.put(OAuth2ConfigBean.PASSWORD_KEY, Collections.singletonList(clientSecret));
    params.put(OAuth2ConfigBean.GRANT_TYPE_KEY, Collections.singletonList(OAuth2ConfigBean.RESOURCE_OWNER_GRANT));
    configBean.username = () -> clientId;
    configBean.password = () -> clientSecret;
  }

  configBean.credentialsGrantType = grantType;
  configBean.transferEncoding = RequestEntityProcessing.BUFFERED;
  configBean.tokenUrl = "https://example.com";

  Mockito.when(response.readEntity(String.class)).thenReturn(TOKEN_RESPONSE);
  Mockito.when(response.getStatus()).thenReturn(200);
  Mockito.when(builder.post(Mockito.argThat(new FormMatcher(Entity.form(params))))).thenReturn(response);
  Mockito.when(builder.property(ClientProperties.REQUEST_ENTITY_PROCESSING, transferEncoding)).thenReturn(builder);
  Mockito.when(builder.header(any(String.class), any(Object.class))).thenReturn(builder);
  Mockito.when(target.request()).thenReturn(builder);

  Mockito.when(client.target(configBean.tokenUrl)).thenReturn(target);
  return configBean;
}
 
Example 9
Source File: RestJobTest.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleGetWithMultipleEventsAndHeadersUsingJsonHandler() throws JobExecutionException {
    String goodUrl = "GOOD URL";
    Map<String, Object> properties = new HashMap<String, Object>();
    MultivaluedMap<String, String> responseHeaders = new MultivaluedMapImpl();
    responseHeaders.put("header1", Arrays.asList("value1", "value2"));
    properties.put(RestSource.CONF_URL, goodUrl);
    properties.put(RestSource.CONF_HEADERS, "{}");
    properties.put(RestSource.CONF_METHOD, "GET");
    String jsonResponse = "[{\"field1\":\"value1\"},{\"field2\":\"value2\"}]";

    restSourceHandler = initJsonHandler("");
    urlHandler = new DefaultUrlHandler();
    when(schedulerContext.get("urlHandler")).thenReturn(urlHandler);
    when(client.resource(goodUrl)).thenReturn(webResource);
    when(response.getEntity(String.class)).thenReturn(jsonResponse);
    when(response.getHeaders()).thenReturn(responseHeaders);
    when(schedulerContext.get("properties")).thenReturn(properties);
    when(schedulerContext.get("restSourceHandler")).thenReturn(restSourceHandler);

    job.execute(context);

    assertThat(queue.size()).isEqualTo(2);
    Event poll = queue.poll();
    assertThat(new String(poll.getBody())).isEqualTo("{\"field1\":\"value1\"}");
    assertThat(poll.getHeaders()).includes(entry("header1", "value1, value2"));
    poll = queue.poll();
    assertThat(new String(poll.getBody())).isEqualTo("{\"field2\":\"value2\"}");
    assertThat(poll.getHeaders()).includes(entry("header1", "value1, value2"));
}
 
Example 10
Source File: HmacAuthInterceptor.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
public void addHeader(Message message, String name, String value) {
    HttpHeaders requestHeaders = new HttpHeadersImpl(message);
    MultivaluedMap<String, String> newHeaders = new MetadataMap<String, String>();
    newHeaders.putAll(requestHeaders.getRequestHeaders());
    newHeaders.put(name, Arrays.asList(value));
    message.put(Message.PROTOCOL_HEADERS, newHeaders);
}
 
Example 11
Source File: TestFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(
    ContainerRequestContext requestContext,
    ContainerResponseContext responseContext) throws IOException {

    MultivaluedMap<String, Object> headers = responseContext.getHeaders();

    headers.put("Filtered", Collections.singletonList("true"));
}
 
Example 12
Source File: TestFilterAndExceptionMapper.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(
    ContainerRequestContext requestContext,
    ContainerResponseContext responseContext) throws IOException {

    MultivaluedMap<String, Object> headers = responseContext.getHeaders();

    headers.put("Filtered", Collections.singletonList("true"));
}
 
Example 13
Source File: HeaderClientFilter.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException
{
  final MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
  List<Object> hcookies = headers.get(COOKIE_HEADER);
  if (hcookies == null) {
    hcookies = new ArrayList<>();
  }
  hcookies.addAll(cookies);
  headers.put(COOKIE_HEADER, hcookies);
  return getNext().handle(clientRequest);
}
 
Example 14
Source File: ParaClient.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Searches for objects that have similar property values to a given text. A "find like this" query.
 * @param <P> type of the object
 * @param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()}
 * @param filterKey exclude an object with this key from the results (optional)
 * @param fields a list of property names
 * @param liketext text to compare to
 * @param pager a {@link com.erudika.para.utils.Pager}
 * @return a list of objects found
 */
public <P extends ParaObject> List<P> findSimilar(String type, String filterKey, String[] fields, String liketext,
		Pager... pager) {
	MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
	params.put("fields", fields == null ? null : Arrays.asList(fields));
	params.putSingle("filterid", filterKey);
	params.putSingle("like", liketext);
	params.putSingle(Config._TYPE, type);
	params.putAll(pagerToParams(pager));
	return getItems(find("similar", params), pager);
}
 
Example 15
Source File: ShopifyErrorResponseExceptionTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenResponseWith422StatusCodeAndSomeResponseBodyAndSomeResponsHeadersWhenCreatingShopifyErroResponseExceptionWithParsableBodyThenCreateExceptionWithExpectedMessageAndException() {
	final Response response = mock(Response.class);
	final int expectedStatusCode = 422;
	when(response.getStatus()).thenReturn(expectedStatusCode);

	final MultivaluedMap<String, String> responseHeaders = new MultivaluedHashMap<>();
	responseHeaders.put("Content-Type", Arrays.asList("application/json", "charset=utf-8"));
	responseHeaders.put("Transfer-Encoding", Arrays.asList("chunked"));
	responseHeaders.put("X-Request-Id", Arrays.asList("ce729803-84ce-4063-a672-816f03c2c9a2"));
	responseHeaders.put("X-Shopify-API-Deprecated-Reason",
			Arrays.asList("https://help.shopify.com/api/guides/inventory-migration-guide"));
	when(response.getStringHeaders()).thenReturn(responseHeaders);

	final String expectedResponseBodyString = "{\n" + "    \"errors\": {\n" + "        \"shipping_address\": [\n"
			+ "            \"address1 can't be blank, zip is not valid for united states, and city can't be blank\"\n"
			+ "        ]\n" + "    }\n" + "}";

	when(response.readEntity(String.class)).thenReturn(expectedResponseBodyString);
	final ShopifyErrorResponseException actualShopifyErrorResponseException = new ShopifyErrorResponseException(
			response);

	final String expectedResponseHeaders = "{Transfer-Encoding=[chunked], X-Request-Id=[ce729803-84ce-4063-a672-816f03c2c9a2], X-Shopify-API-Deprecated-Reason=[https://help.shopify.com/api/guides/inventory-migration-guide], Content-Type=[application/json, charset=utf-8]}";

	assertEquals(String.format(ShopifyErrorResponseException.MESSAGE, expectedStatusCode, expectedResponseHeaders,
			expectedResponseBodyString), actualShopifyErrorResponseException.getMessage());
	assertTrue(actualShopifyErrorResponseException instanceof RuntimeException);
	assertEquals(1, actualShopifyErrorResponseException.getShopifyErrorCodes().size());
	assertEquals(Type.SHIPPING_ADDRESS,
			actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getType());
	assertEquals("address1 can't be blank, zip is not valid for united states, and city can't be blank",
			actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getMessage());
	assertEquals(expectedStatusCode, actualShopifyErrorResponseException.getStatusCode());
	assertEquals(expectedResponseBodyString, actualShopifyErrorResponseException.getResponseBody());
}
 
Example 16
Source File: ShopifyErrorResponseExceptionTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenResponseWith422StatusCodeAndSomeResponseBodyAndSomeResponsHeadersWhenCreatingShopifyErroResponseExceptionWithUnparseableBodyThenCreateExceptionWithExpectedMessageAndException() {
	final Response response = mock(Response.class);
	final int expectedStatusCode = 422;
	when(response.getStatus()).thenReturn(expectedStatusCode);

	final MultivaluedMap<String, String> responseHeaders = new MultivaluedHashMap<>();
	responseHeaders.put("Content-Type", Arrays.asList("application/json", "charset=utf-8"));
	responseHeaders.put("Transfer-Encoding", Arrays.asList("chunked"));
	responseHeaders.put("X-Request-Id", Arrays.asList("ce729803-84ce-4063-a672-816f03c2c9a2"));
	responseHeaders.put("X-Shopify-API-Deprecated-Reason",
			Arrays.asList("https://help.shopify.com/api/guides/inventory-migration-guide"));
	when(response.getStringHeaders()).thenReturn(responseHeaders);

	final String expectedResponseBodyString = "Some unaprseable error";
	when(response.readEntity(String.class)).thenReturn(expectedResponseBodyString);
	final ShopifyErrorResponseException actualShopifyErrorResponseException = new ShopifyErrorResponseException(
			response);

	final String expectedResponseHeaders = "{Transfer-Encoding=[chunked], X-Request-Id=[ce729803-84ce-4063-a672-816f03c2c9a2], X-Shopify-API-Deprecated-Reason=[https://help.shopify.com/api/guides/inventory-migration-guide], Content-Type=[application/json, charset=utf-8]}";

	assertEquals(String.format(ShopifyErrorResponseException.MESSAGE, expectedStatusCode, expectedResponseHeaders,
			expectedResponseBodyString), actualShopifyErrorResponseException.getMessage());
	assertTrue(actualShopifyErrorResponseException instanceof RuntimeException);
	assertEquals(1, actualShopifyErrorResponseException.getShopifyErrorCodes().size());
	assertEquals(Type.UNKNOWN, actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getType());
	assertEquals(expectedResponseBodyString,
			actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getMessage());
	assertEquals(expectedStatusCode, actualShopifyErrorResponseException.getStatusCode());
	assertEquals(expectedResponseBodyString, actualShopifyErrorResponseException.getResponseBody());
}
 
Example 17
Source File: ShopifyErrorResponseExceptionTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenResponseWith422StatusCodeAndSomeResponseBodyAndSomeResponsHeadersWhenCreatingShopifyErroResponseExceptionThenCreateExceptionWithExpectedMessageAndException() {
	final Response response = mock(Response.class);
	final int expectedStatusCode = 422;
	when(response.getStatus()).thenReturn(expectedStatusCode);

	final MultivaluedMap<String, String> responseHeaders = new MultivaluedHashMap<>();
	responseHeaders.put("Content-Type", Arrays.asList("application/json", "charset=utf-8"));
	responseHeaders.put("Transfer-Encoding", Arrays.asList("chunked"));
	responseHeaders.put("X-Request-Id", Arrays.asList("ce729803-84ce-4063-a672-816f03c2c9a2"));
	responseHeaders.put("X-Shopify-API-Deprecated-Reason",
			Arrays.asList("https://help.shopify.com/api/guides/inventory-migration-guide"));
	when(response.getStringHeaders()).thenReturn(responseHeaders);

	final String expectedResponseBodyString = "{\"error\": \"something went wrong.\"}";
	when(response.readEntity(String.class)).thenReturn(expectedResponseBodyString);

	final ShopifyErrorResponseException actualShopifyErrorResponseException = new ShopifyErrorResponseException(
			response);

	final String expectedResponseHeaders = "{Transfer-Encoding=[chunked], X-Request-Id=[ce729803-84ce-4063-a672-816f03c2c9a2], X-Shopify-API-Deprecated-Reason=[https://help.shopify.com/api/guides/inventory-migration-guide], Content-Type=[application/json, charset=utf-8]}";

	assertEquals(String.format(ShopifyErrorResponseException.MESSAGE, expectedStatusCode, expectedResponseHeaders,
			expectedResponseBodyString), actualShopifyErrorResponseException.getMessage());
	assertTrue(actualShopifyErrorResponseException instanceof RuntimeException);
	assertEquals(1, actualShopifyErrorResponseException.getShopifyErrorCodes().size());
	assertEquals(Type.UNKNOWN, actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getType());
	assertEquals(expectedResponseBodyString,
			actualShopifyErrorResponseException.getShopifyErrorCodes().get(0).getMessage());
	assertEquals(expectedStatusCode, actualShopifyErrorResponseException.getStatusCode());
	assertEquals(expectedResponseBodyString, actualShopifyErrorResponseException.getResponseBody());
}
 
Example 18
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getMultipleHeaderAsStringAndUsesRuntimeDelegateForConvertValuesToString() throws Exception {
    HeaderDelegate<HeaderValue> headerDelegate = mock(HeaderDelegate.class);
    when(headerDelegate.toString(isA(HeaderValue.class))).thenReturn("bar1", "bar2");
    RuntimeDelegate runtimeDelegate = mock(RuntimeDelegate.class);
    when(runtimeDelegate.createHeaderDelegate(HeaderValue.class)).thenReturn(headerDelegate);
    RuntimeDelegate.setInstance(runtimeDelegate);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.put("foo", newArrayList(new HeaderValue(), new HeaderValue()));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals("bar1,bar2", response.getHeaderString("foo"));
}
 
Example 19
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getsLinks() throws Exception {
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    Link link = new LinkBuilderImpl().uri("http://localhost:8080/x/y/z").rel("xxx").build();
    headers.put(LINK, newArrayList(link));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(newHashSet(link), response.getLinks());
}
 
Example 20
Source File: ParaClient.java    From para with Apache License 2.0 3 votes vote down vote up
/**
 * Searches for objects having a property value that is in list of possible values.
 * @param <P> type of the object
 * @param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()}
 * @param field the property name of an object
 * @param terms a list of terms (property values)
 * @param pager a {@link com.erudika.para.utils.Pager}
 * @return a list of objects found
 */
public <P extends ParaObject> List<P> findTermInList(String type, String field, List<String> terms, Pager... pager) {
	MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
	params.putSingle("field", field);
	params.put("terms", terms);
	params.putSingle(Config._TYPE, type);
	params.putAll(pagerToParams(pager));
	return getItems(find("in", params), pager);
}