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

The following examples show how to use javax.ws.rs.core.MultivaluedMap#putSingle() . 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: AsynchronousRequestTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void providesListOfAsynchronousJobsAsPlainText() throws Exception {
    processor.addApplication(new Application() {
        @Override
        public Set<Class<?>> getClasses() {
            return newHashSet(Resource1.class);
        }
    });
    startAsynchronousJobAndGetItsUrl("/a", "GET", null, null, null);

    MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
    headers.putSingle("accept", "text/plain");
    ContainerResponse response = launcher.service("GET", "/async", "", headers, null, null, null);

    assertEquals(200, response.getStatus());
    assertEquals("text/plain", response.getContentType().toString());

    Collection<AsynchronousProcess> processes = (Collection<AsynchronousProcess>)response.getEntity();

    assertEquals(1, processes.size());
    AsynchronousProcess process = processes.iterator().next();
    assertNull(process.getOwner());
    assertEquals("running", process.getStatus());
    assertEquals("/a", process.getPath());
}
 
Example 2
Source File: UtilsTest.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testLimitParam () {
    MultivaluedMap<String, String> formParams = new MultivaluedHashMap<>();
    LimitParam instance = LimitParam.valueOf(formParams);
    assertEquals(instance.getLimit(), Integer.valueOf(25));
    assertEquals(instance.getStart(), Integer.valueOf(0));
    formParams.putSingle("offset", "test");
    instance = LimitParam.valueOf(formParams);
    assertEquals(instance.getLimit(), Integer.valueOf(25));
    assertEquals(instance.getStart(), Integer.valueOf(0));
    formParams.putSingle("offset", "50");
    instance = LimitParam.valueOf(formParams);
    assertEquals(instance.getLimit(), Integer.valueOf(25));
    assertEquals(instance.getStart(), Integer.valueOf(0));
    formParams.putSingle("limit", "100");
    instance = LimitParam.valueOf(formParams);
    assertEquals(instance.getLimit(), Integer.valueOf(100));
    assertEquals(instance.getStart(), Integer.valueOf(50));
    formParams.remove("offset");
    instance = LimitParam.valueOf(formParams);
    assertEquals(instance.getLimit(), Integer.valueOf(100));
    assertEquals(instance.getStart(), Integer.valueOf(0));
}
 
Example 3
Source File: SerializationProvider.java    From Web-API with MIT License 6 votes vote down vote up
@Override
protected void _modifyHeaders(Object value, Class<?> type, Type genericType, Annotation[] annotations,
                              MultivaluedMap<String, Object> httpHeaders, JsonEndpointConfig endpoint)
        throws IOException {
    super._modifyHeaders(value, type, genericType, annotations, httpHeaders, endpoint);

    // If the mapper was changed with a query parameter, we have to update
    // the content type header to reflect that
    Map<String, String> queryParams = Util.getQueryParams(request);
    if (queryParams.containsKey("accept")) {
        String acc = queryParams.get("accept");
        if (acc.equalsIgnoreCase("json")) {
            httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        }
        if (acc.equalsIgnoreCase("xml")) {
            httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
        }
    }
}
 
Example 4
Source File: ParseRequestStageTest.java    From agrest with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_Sort_Dupes() {

    MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
    params.putSingle("sort", "[{\"property\":\"a\",\"direction\":\"DESC\"},{\"property\":\"a\",\"direction\":\"ASC\"}]");
    SelectContext<Tr> context = prepareContext(Tr.class, params);

    stage.execute(context);

    assertNotNull(context.getMergedRequest());
    assertNotNull(context.getMergedRequest().getOrderings());
    assertEquals(2, context.getMergedRequest().getOrderings().size());

    Sort o1 = context.getMergedRequest().getOrderings().get(0);
    Sort o2 = context.getMergedRequest().getOrderings().get(1);

    assertEquals("a", o1.getProperty());
    assertEquals(Dir.DESC, o1.getDirection());
    assertEquals("a", o2.getProperty());
    assertEquals(Dir.ASC, o2.getDirection());
}
 
Example 5
Source File: ODataExceptionMapperImplTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtendedODataErrorContext() throws Exception {
  MultivaluedMap<String, String> value = new MultivaluedHashMap<String, String>();
  value.putSingle("Accept", "AcceptValue");
  value.put("AcceptMulti", Arrays.asList("AcceptValue_1", "AcceptValue_2"));
  when(exceptionMapper.httpHeaders.getRequestHeaders()).thenReturn(value);
  when(exceptionMapper.servletConfig.getInitParameter(ODataServiceFactory.FACTORY_LABEL)).thenReturn(
      ODataServiceFactoryWithCallbackImpl.class.getName());
  when(exceptionMapper.servletRequest.getAttribute(ODataServiceFactory.FACTORY_CLASSLOADER_LABEL)).thenReturn(null);
  Response response = exceptionMapper.toResponse(new Exception());

  // verify
  assertNotNull(response);
  assertEquals(HttpStatusCodes.BAD_REQUEST.getStatusCode(), response.getStatus());
  String errorMessage = (String) response.getEntity();
  assertEquals("bla", errorMessage);
  String contentTypeHeader = response.getHeaderString(org.apache.olingo.odata2.api.commons.HttpHeaders.CONTENT_TYPE);
  assertEquals("text/html", contentTypeHeader);
  //
  assertEquals(uri.toASCIIString(), response.getHeaderString("RequestUri"));
  assertEquals("[AcceptValue]", response.getHeaderString("Accept"));
  assertEquals("[AcceptValue_1, AcceptValue_2]", response.getHeaderString("AcceptMulti"));
}
 
Example 6
Source File: KerberosStandaloneTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-3451
 *
 * Test that if there is no User Storage Provider that can handle kerberos we can still login
 *
 * @throws Exception
 */
@Test
public void noProvider() throws Exception {
    List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
    org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
    ComponentRepresentation kerberosProvider = reps.get(0);
    testRealmResource().components().component(kerberosProvider.getId()).remove();

    /*
     To do this we do a valid kerberos login.  The authenticator will obtain a valid token, but there will
     be no user storage provider that can process it.  This means we should be on the login page.
     We do this through a JAX-RS client request.  We extract the action URL from the login page, and stuff it
     into selenium then just perform a regular login.
     */
    Response spnegoResponse = spnegoLogin("hnelson", "secret");
    String context = spnegoResponse.readEntity(String.class);
    spnegoResponse.close();

    Assert.assertTrue(context.contains("Log in to test"));

    String url = ActionURIUtils.getActionURIFromPageSource(context);


    // Follow login with HttpClient. Improve if needed
    MultivaluedMap<String, String> params = new javax.ws.rs.core.MultivaluedHashMap<>();
    params.putSingle("username", "test-user@localhost");
    params.putSingle("password", "password");
    Response response = client.target(url).request()
            .post(Entity.form(params));

    URI redirectUri = response.getLocation();
    assertAuthenticationSuccess(redirectUri.toString());

    events.clear();
    testRealmResource().components().add(kerberosProvider);
}
 
Example 7
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testLargerThanDefaultHeader() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/image";
    WebClient client = WebClient.create(address);
    client.type("multipart/mixed").accept("multipart/mixed");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");

    StringBuilder sb = new StringBuilder(64);
    sb.append("form-data;");
    for (int i = 0; i < 35; i++) {
        sb.append("aaaaaaaaaa");
    }

    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    headers.putSingle("Content-ID", "root");
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-Disposition", sb.toString());
    DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream"));

    Attachment att = new Attachment(headers, handler, null);
    Response response = client.post(att);
    assertEquals(response.getStatus(), 200);

    client.close();
}
 
Example 8
Source File: WebClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
private MultivaluedMap<String, String> prepareHeaders(Class<?> responseClass, Object body) {
    MultivaluedMap<String, String> headers = getHeaders();
    if (headers.getFirst(HttpHeaders.CONTENT_TYPE) == null && body instanceof Form) {
        headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
    }

    if (responseClass != null && responseClass != Response.class
        && headers.getFirst(HttpHeaders.ACCEPT) == null) {
        headers.putSingle(HttpHeaders.ACCEPT, MediaType.WILDCARD);
    }
    return headers;
}
 
Example 9
Source File: ServerHeaderFilter.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
		throws IOException {
	MultivaluedMap<String, Object> headers = response.getHeaders();
	headers.putSingle(Header.Server.toString(), "GRZLY"); // The same as raw
															// Grizzly test
															// implementation
	headers.putSingle(Header.Date.toString(), FastHttpDateFormat.getCurrentDate());
}
 
Example 10
Source File: IdTranslatorConfiguration.java    From datawave with Apache License 2.0 5 votes vote down vote up
public MultivaluedMap<String,String> optionalParamsToMap() {
    MultivaluedMap<String,String> p = new MultivaluedMapImpl<>();
    if (this.columnVisibility != null) {
        p.putSingle(QueryParameters.QUERY_VISIBILITY, this.columnVisibility);
    }
    return p;
}
 
Example 11
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getsContentLength() throws Exception {
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.putSingle(CONTENT_LENGTH, 3);
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(3, response.getLength());
}
 
Example 12
Source File: StringValueOfProducerTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void createsInstanceAndUsesSingleValueFromMap() throws Exception {
    MultivaluedMap<String, String> values = new MultivaluedMapImpl();
    values.putSingle("number", "2147483647");

    Object result = producer.createValue("number", values, null);
    assertEquals(new Integer("2147483647"), result);
}
 
Example 13
Source File: DcCoreContainerFilter.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 全てのレスポンスに共通するレスポンスヘッダーを追加する.
 * Access-Control-Allow-Origin, Access-Control-Allow-Headers<br/>
 * X-Dc-Version<br/>
 * @param request
 * @param response
 */
private void addResponseHeaders(final ContainerRequest request, final ContainerResponse response) {
    MultivaluedMap<String, Object> mm = response.getHttpHeaders();
    String acrh = request.getHeaderValue(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    if (acrh != null) {
        mm.putSingle(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, acrh);
    } else {
        mm.remove(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS);
    }
    mm.putSingle(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.Value.ASTERISK);
    // X-Dc-Version
    mm.putSingle(HttpHeaders.X_DC_VERSION, DcCoreConfig.getCoreVersion());
}
 
Example 14
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testLargeHeader() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/image";
    WebClient client = WebClient.create(address);
    client.type("multipart/mixed").accept("multipart/mixed");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");

    StringBuilder sb = new StringBuilder(100500);
    sb.append("form-data;");
    for (int i = 0; i < 10000; i++) {
        sb.append("aaaaaaaaaa");
    }

    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    headers.putSingle("Content-ID", "root");
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-Disposition", sb.toString());
    DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream"));

    Attachment att = new Attachment(headers, handler, null);
    Response response = client.post(att);
    assertEquals(response.getStatus(), 413);

    client.close();
}
 
Example 15
Source File: PrincipalFactoryTest.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
@Test
public final void verifyProvideAppliesContentToSignature() throws URISyntaxException, UnsupportedEncodingException {
    // given
    final MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>();
    parameterMap.putSingle("apiKey", "validApiKey");

    final URI uri = new URI("https://api.example.com/path/to/resource?apiKey=validApiKey");
    final ExtendedUriInfo uriInfo = mock(ExtendedUriInfo.class);
    given(uriInfo.getQueryParameters()).willReturn(parameterMap);
    given(uriInfo.getRequestUri()).willReturn(uri);

    given(request.getUriInfo()).willReturn(uriInfo);
    given(request.getHeaderString("X-Auth-Version")).willReturn("1");
    given(request.getHeaderString("X-Auth-Signature")).willReturn("validSignature");
    given(request.getHeaderString("X-Auth-Timestamp")).willReturn("two seconds ago");
    given(request.getMethod()).willReturn("PUT");
    given(request.hasEntity()).willReturn(true);
    given(request.getEntityStream()).willReturn(new ByteArrayInputStream("content".getBytes("UTF-8")));

    given(authenticator.authenticate(any(Credentials.class))).willReturn("principal");

    // when
    final String result = factory.provide();

    // then
    assertEquals("principal", result);
    final ArgumentCaptor<Credentials> credentialsCaptor = ArgumentCaptor.forClass(Credentials.class);
    verify(authenticator).authenticate(credentialsCaptor.capture());
    final Credentials credentials = credentialsCaptor.getValue();
    assertEquals("validApiKey", credentials.getApiKey());
    assertEquals("two seconds ago", credentials.getTimestamp());
    assertEquals("PUT", credentials.getMethod());
    assertEquals("/path/to/resource?apiKey=validApiKey", credentials.getPath());
    assertEquals("content", new String(credentials.getContent(), "UTF-8"));
}
 
Example 16
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void parsesContentTypeHeader() throws Exception {
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.putSingle(CONTENT_TYPE, "text/plain;charset=utf-8");
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);

    assertEquals(new MediaType("text", "plain", ImmutableMap.of("charset", "utf-8")), response.getMediaType());
}
 
Example 17
Source File: ParaClient.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all child objects linked to this object.
 * @param <P> the type of children
 * @param type2 the type of children to look for
 * @param field the field name to use as filter
 * @param term the field value to use as filter
 * @param obj the object to execute this method on
 * @param pager a {@link com.erudika.para.utils.Pager}
 * @return a list of {@link ParaObject} in a one-to-many relationship with this object
 */
@SuppressWarnings("unchecked")
public <P extends ParaObject> List<P> getChildren(ParaObject obj, String type2, String field, String term,
		Pager... pager) {
	if (obj == null || obj.getId() == null || type2 == null) {
		return Collections.emptyList();
	}
	MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
	params.putSingle("childrenonly", "true");
	params.putSingle("field", field);
	params.putSingle("term", term);
	params.putAll(pagerToParams(pager));
	String url = Utils.formatMessage("{0}/links/{1}", obj.getObjectURI(), Utils.urlEncode(type2));
	return getItems((Map<String, Object>) getEntity(invokeGet(url, params), Map.class), pager);
}
 
Example 18
Source File: ResourceOwnerGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public MultivaluedMap<String, String> toMap() {
    MultivaluedMap<String, String> map = super.toMap();
    map.putSingle(OAuthConstants.RESOURCE_OWNER_NAME, ownerName);
    map.putSingle(OAuthConstants.RESOURCE_OWNER_PASSWORD, ownerPassword);

    return map;
}
 
Example 19
Source File: Saml2BearerGrant.java    From cxf with Apache License 2.0 4 votes vote down vote up
public MultivaluedMap<String, String> toMap() {
    MultivaluedMap<String, String> map = initMap();
    map.putSingle(Constants.CLIENT_GRANT_ASSERTION_PARAM, encodeAssertion());
    addScope(map);
    return map;
}
 
Example 20
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddBookJsonImageStream() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/jsonimagestream";
    WebClient client = WebClient.create(address);
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    client.type("multipart/mixed").accept("multipart/mixed");

    Book json = new Book("json", 1L);
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    Map<String, Object> objects = new LinkedHashMap<>();

    MultivaluedMap<String, String> headers = new MetadataMap<>();

    headers = new MetadataMap<>();
    headers.putSingle("Content-Type", "application/json");
    headers.putSingle("Content-ID", "thejson");
    headers.putSingle("Content-Transfer-Encoding", "customjson");
    Attachment attJson = new Attachment(headers, json);

    headers = new MetadataMap<>();
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-ID", "theimage");
    headers.putSingle("Content-Transfer-Encoding", "customstream");
    Attachment attIs = new Attachment(headers, is1);

    objects.put(MediaType.APPLICATION_JSON, attJson);
    objects.put(MediaType.APPLICATION_OCTET_STREAM, attIs);

    Collection<? extends Attachment> coll = client.postAndGetCollection(objects, Attachment.class);
    List<Attachment> result = new ArrayList<>(coll);
    assertEquals(2, result.size());
    Book json2 = readJSONBookFromInputStream(result.get(0).getDataHandler().getInputStream());
    assertEquals("json", json2.getName());
    assertEquals(1L, json2.getId());
    InputStream is2 = result.get(1).getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);
}