javax.ws.rs.core.MultivaluedHashMap Java Examples

The following examples show how to use javax.ws.rs.core.MultivaluedHashMap. 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: PaginationLinkTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testLastPageSpecificSize() throws URISyntaxException {
    Integer page = 8;
    Integer size = 15;
    Integer totalItems = 120;

    MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();
    queryParameters.putSingle(PaginationParam.PAGE_QUERY_PARAM_NAME, page.toString());
    queryParameters.putSingle(PaginationParam.SIZE_QUERY_PARAM_NAME, size.toString());

    doReturn(new URI(path + "?page=" + page + "&size=" + size)).when(uriInfo).getRequestUri();
    doReturn(queryParameters).when(uriInfo).getQueryParameters();

    String expectedSelf = path + "?page=8&size=15";
    String expectedFirst = path + "?page=1&size=15";
    String expectedPrev = path + "?page=7&size=15";
    String expectedNext = null;
    String expectedLast = path + "?page=8&size=15";

    testGenericPaginatedLinks(page, size, totalItems, expectedSelf, expectedFirst, expectedPrev, expectedNext, expectedLast);
}
 
Example #2
Source File: CorsFilterTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Test
public void corsResponseFilter_EmptyExposedHeadersGiven_DoesNotAddExposeHeadersHeader() throws IOException {
	CorsFilter filter = new CorsFilter.Builder()
			.exposeHeaders(Collections.emptySet())
			.build();

	ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET);
	ContainerResponseContext response = mock(ContainerResponseContext.class);
	MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
	when(response.getHeaders()).thenReturn(headers);
	filter.filter(request, response);

	assertNull(headers.getFirst(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));

	verify(response).getHeaders();
	verifyZeroInteractions(response);
}
 
Example #3
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 #4
Source File: EdgeAPI.java    From hugegraph-client with Apache License 2.0 6 votes vote down vote up
public List<String> create(List<Edge> edges, boolean checkVertex) {
    MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.putSingle("Content-Encoding", BATCH_ENCODING);
    Map<String, Object> params = ImmutableMap.of("check_vertex",
                                                 checkVertex);
    RestResult result = this.client.post(this.batchPath(), edges,
                                         headers, params);
    List<String> ids = result.readList(String.class);
    if (edges.size() != ids.size()) {
        throw new NotAllCreatedException(
                  "Not all edges are successfully created, " +
                  "expect '%s', the actual is '%s'",
                  ids, edges.size(), ids.size());
    }
    return ids;
}
 
Example #5
Source File: SelectBuilderIT.java    From agrest with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetIncludedObjects_Related() {

    Ts ts1 = new Ts(11, "p");
    Ts ts2 = new Ts(12, "q");
    Ts ts3 = new Ts(13, "r");

    bucket(Ts.class).put(11, ts1);
    bucket(Ts.class).put(12, ts1);
    bucket(Ts.class).put(13, ts1);

    bucket(Tr.class).put(1, new Tr(1, "a", ts1, ts2));
    bucket(Tr.class).put(2, new Tr(2, "b", ts3));
    bucket(Tr.class).put(3, new Tr(3, "c"));

    MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
    params.putSingle("include", "{\"path\":\"rtss\",\"sort\":\"id\"}");

    UriInfo mockUri = mock(UriInfo.class);
    when(mockUri.getQueryParameters()).thenReturn(params);

    DataResponse<Tr> response = ag().select(Tr.class).uri(mockUri).get();
    String names = response.getIncludedObjects(Ts.class, "rtss").stream().map(Ts::getName).collect(joining(","));

    assertEquals("p,q,r", names);
}
 
Example #6
Source File: PaginationLinkTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultParams() throws URISyntaxException {
    Integer page = 1;
    Integer size = 10;
    Integer totalItems = 120;

    MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();

    doReturn(new URI(path)).when(uriInfo).getRequestUri();
    doReturn(queryParameters).when(uriInfo).getQueryParameters();

    String expectedSelf = path;
    String expectedFirst = path + "?page=1";
    String expectedPrev = null;
    String expectedNext = path + "?page=2";
    String expectedLast = path + "?page=12";

    testGenericPaginatedLinks(page, size, totalItems, expectedSelf, expectedFirst, expectedPrev, expectedNext, expectedLast);
}
 
Example #7
Source File: ContainerResponseTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void writesResponseWhenResponseEntityIsNotNullRequestMethodIsGETAcceptHeaderIsNotSetAndContentTypeIsNotSet() throws Exception {
    when(providers.getMessageBodyWriter(String.class, String.class, null, TEXT_PLAIN_TYPE)).thenReturn(new StringEntityProvider());
    when(providers.getAcceptableWriterMediaTypes(String.class, String.class, null)).thenReturn(newArrayList(TEXT_PLAIN_TYPE));
    when(containerRequest.getMethod()).thenReturn("GET");
    when(containerRequest.getAcceptableMediaTypes()).thenReturn(newArrayList(WILDCARD_TYPE));
    when(containerRequest.getAcceptableMediaType(newArrayList(TEXT_PLAIN_TYPE))).thenReturn(TEXT_PLAIN_TYPE);

    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    Response response = mockResponse(200, headers, "foo");
    containerResponse.setResponse(response);

    containerResponse.writeResponse();

    assertEquals(200, containerResponse.getStatus());
    verify(containerResponseWriter).writeHeaders(containerResponse);
    verify(containerResponseWriter).writeBody(same(containerResponse), any(MessageBodyWriter.class));
}
 
Example #8
Source File: QueryParametersTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeTests() {
    beginDate = new Date(accumuloDate);
    endDate = new Date(nifiDate);
    expDate = new Date(nifiDate);
    logicName = "QueryTest";
    pagesize = 1;
    persistenceMode = QueryPersistence.PERSISTENT;
    query = "WHEREIS:Waldo";
    queryName = "myQueryForTests";
    requestHeaders = new MultivaluedHashMap<String,String>();
    requestHeaders.add(headerName, headerValue);
    trace = true;
    
    // Build initial QueryParameters
    qp = buildQueryParameters();
}
 
Example #9
Source File: MatrixParameterResolverTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    matrixParameters = new MultivaluedHashMap<>();
    matrixParameters.putSingle("foo", "to be or not to be");
    matrixParameters.putSingle("bar", "hello world");

    PathSegment firstPathSegment = mock(PathSegment.class);
    PathSegment lastPathSegment = mock(PathSegment.class);
    when(lastPathSegment.getMatrixParameters()).thenReturn(matrixParameters);

    applicationContext = mock(ApplicationContext.class, RETURNS_DEEP_STUBS);
    when(applicationContext.getUriInfo().getPathSegments(true)).thenReturn(newArrayList(firstPathSegment, lastPathSegment));

    MatrixParam matrixParamAnnotation = mock(MatrixParam.class);
    when(matrixParamAnnotation.value()).thenReturn("foo");

    parameter = mock(Parameter.class);
    when(parameter.getParameterClass()).thenReturn((Class)String.class);

    typeProducer = mock(TypeProducer.class);
    TypeProducerFactory typeProducerFactory = mock(TypeProducerFactory.class);
    when(typeProducerFactory.createTypeProducer(eq(String.class), any())).thenReturn(typeProducer);

    matrixParameterResolver = new MatrixParameterResolver(matrixParamAnnotation, typeProducerFactory);
}
 
Example #10
Source File: InboundSseEventImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private <T> T read(Class<T> messageType, Type type, MediaType mediaType) {
    if (data == null) {
        return null;
    }

    final Annotation[] annotations = new Annotation[0];
    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(0);
    
    final MessageBodyReader<T> reader = factory.createMessageBodyReader(messageType, type, 
        annotations, mediaType, message);
        
    if (reader == null) {
        throw new RuntimeException("No suitable message body reader for class: " + messageType.getName());
    }

    try (ByteArrayInputStream is = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))) {
        return reader.readFrom(messageType, type, annotations, mediaType, headers, is);
    } catch (final IOException ex) {
        throw new RuntimeException("Unable to read data of type " + messageType.getName(), ex);
    }
}
 
Example #11
Source File: UrlFormEncodedBodyWriterTest.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void test() throws IOException {
    EnkanSystem system = EnkanSystem.of("beans", new JacksonBeansConverter());
    system.start();
    Map<String, SystemComponent> components = new HashMap<String, SystemComponent>() {{
        put("beans", system.getComponent("beans"));
    }};
    ComponentInjector injector = new ComponentInjector(components);
    UrlFormEncodedBodyWriter bodyWriter = new UrlFormEncodedBodyWriter();
    injector.inject(bodyWriter);

    TestDto dto = new TestDto();
    dto.setA(8);
    dto.setB("あいうえお");
    try(ByteArrayOutputStream entityStream = new ByteArrayOutputStream()) {
        bodyWriter.writeTo(dto, TestDto.class, TestDto.class, null, new MediaType("", ""),
                new MultivaluedHashMap<>(), entityStream);

        String out = new String(entityStream.toByteArray());
        Parameters params = CodecUtils.formDecode(out, "UTF-8");
        assertThat(params.getLong("a")).isEqualTo(8);
        assertThat(params.get("b")).isEqualTo("あいうえお");
    }
}
 
Example #12
Source File: ContainerFeatureSetRequestFilterTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotSetFeatureSet_withNoHeader() throws Exception {
    // Given
    mockStatic(FeaturesContextHolder.class);
    final ContainerRequestContext mockContainerRequestContext = mock(ContainerRequestContext.class);
    final MultivaluedMap<String, String> headersMap = new MultivaluedHashMap<>();
    when(mockContainerRequestContext.getHeaders()).thenReturn(headersMap);
    final ContainerFeatureSetRequestFilter containerFeatureSetRequestFilter = new ContainerFeatureSetRequestFilter();

    // When
    containerFeatureSetRequestFilter.filter(mockContainerRequestContext);

    // Then
    verifyStatic(FeaturesContextHolder.class);
    FeaturesContextHolder.clear();
}
 
Example #13
Source File: XACMLRequestFilterTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void resourceIdFormDataExistsWithDefaultTest() throws Exception {
    FormDataMultiPart formPart = new FormDataMultiPart();
    formPart.field(FORM_DATA_FIELD, FORM_DATA_VALUE);
    when(context.readEntity(FormDataMultiPart.class)).thenReturn(formPart);
    when(context.hasEntity()).thenReturn(true);
    when(context.getMediaType()).thenReturn(MediaType.MULTIPART_FORM_DATA_TYPE);
    when(uriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
    when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(resourceInfo.getResourceMethod()).thenReturn(MockResourceIdFormDataClass.class.getDeclaredMethod("formDataWithDefault"));

    IRI actionId = VALUE_FACTORY.createIRI(Read.TYPE);
    IRI resourceId = VALUE_FACTORY.createIRI(FORM_DATA_VALUE);
    IRI subjectId = VALUE_FACTORY.createIRI(ANON_USER);

    filter.filter(context);
    Mockito.verify(pdp).createRequest(subjectId, new HashMap<>(), resourceId, new HashMap<>(), actionId, new HashMap<>());
}
 
Example #14
Source File: TrellisWebDAVRequestFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    initMocks(this);

    when(mockBundler.getResourceService()).thenReturn(mockResourceService);
    when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + PATH))))
        .thenAnswer(inv -> completedFuture(MISSING_RESOURCE));
    when(mockContext.getMethod()).thenReturn(PUT);
    when(mockContext.getUriInfo()).thenReturn(mockUriInfo);
    when(mockContext.getHeaders()).thenReturn(mockHeaders);
    when(mockUriBuilder.path(any(String.class))).thenReturn(mockUriBuilder);
    when(mockUriInfo.getBaseUriBuilder()).thenReturn(mockUriBuilder);
    when(mockUriInfo.getPath()).thenReturn(PATH);
    when(mockUriInfo.getPathSegments()).thenReturn(singletonList(mockPathSegment));
    when(mockUriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(mockPathSegment.getPath()).thenReturn(PATH);

    filter = new TrellisWebDAVRequestFilter();
    filter.setServiceBundler(mockBundler);
    filter.setCreateUncontained(true);
    filter.setBaseUrl(null);
}
 
Example #15
Source File: JRestlessHandlerContainerTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerRequest_RequestAndContainerResponseWriterAndSecurityContextGiven_ShouldCreateContainerRequestUsingValues() {
	URI baseUri = URI.create("/");
	URI requestUri = URI.create("/entity");
	String httpMethod = "POST";
	ByteArrayInputStream entityStream = new ByteArrayInputStream(new byte[0]);
	MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
	headers.add("hk0", "hv0_0");
	headers.add("hk0", "hv0_1");
	headers.add("hk1", "hv1_0");
	JRestlessContainerRequest request = createRequest(baseUri, requestUri, httpMethod, entityStream, headers);

	ContainerResponseWriter containerResponseWriter = mock(ContainerResponseWriter.class);
	SecurityContext securityContext = mock(SecurityContext.class);

	ContainerRequest containerRequest = container.createContainerRequest(request, containerResponseWriter, securityContext);

	assertEquals(baseUri, containerRequest.getBaseUri());
	assertEquals(requestUri, containerRequest.getRequestUri());
	assertEquals(httpMethod, containerRequest.getMethod());
	assertSame(entityStream, containerRequest.getEntityStream());
	assertEquals(headers, containerRequest.getHeaders());
	assertSame(containerResponseWriter, containerRequest.getResponseWriter());
	assertSame(securityContext, containerRequest.getSecurityContext());
}
 
Example #16
Source File: TestSnappyWriterInterceptor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testSnappyWriterInterceptor() throws IOException {

  SnappyWriterInterceptor writerInterceptor = new SnappyWriterInterceptor();

  MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
  WriterInterceptorContext mockInterceptorContext = Mockito.mock(WriterInterceptorContext.class);
  Mockito.when(mockInterceptorContext.getHeaders()).thenReturn(headers);
  Mockito.when(mockInterceptorContext.getOutputStream()).thenReturn(new ByteArrayOutputStream());
  Mockito.doNothing().when(mockInterceptorContext).setOutputStream(Mockito.any(OutputStream.class));

  // call aroundWriteTo on mock
  writerInterceptor.aroundWriteTo(mockInterceptorContext);

  // verify that setOutputStream method was called once with argument which is an instance of SnappyFramedOutputStream
  Mockito.verify(mockInterceptorContext, Mockito.times(1))
    .setOutputStream(Mockito.any(SnappyFramedOutputStream.class));

}
 
Example #17
Source File: QueryParameterResolverTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    queryParameters = new MultivaluedHashMap<>();
    queryParameters.putSingle("foo", "aaa");
    queryParameters.putSingle("bar", "bbb");

    applicationContext = mock(ApplicationContext.class, RETURNS_DEEP_STUBS);
    when(applicationContext.getQueryParameters(true)).thenReturn(queryParameters);

    QueryParam queryParamAnnotation = mock(QueryParam.class);
    when(queryParamAnnotation.value()).thenReturn("foo");

    parameter = mock(Parameter.class);
    when(parameter.getParameterClass()).thenReturn((Class)String.class);

    typeProducer = mock(TypeProducer.class);
    TypeProducerFactory typeProducerFactory = mock(TypeProducerFactory.class);
    when(typeProducerFactory.createTypeProducer(eq(String.class), any())).thenReturn(typeProducer);

    queryParameterResolver = new QueryParameterResolver(queryParamAnnotation, typeProducerFactory);
}
 
Example #18
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterResponseBaseUrl() {
    final MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    final MultivaluedMap<String, String> stringHeaders = new MultivaluedHashMap<>();
    when(mockResponseContext.getStatusInfo()).thenReturn(OK);
    when(mockResponseContext.getHeaders()).thenReturn(headers);
    when(mockResponseContext.getStringHeaders()).thenReturn(stringHeaders);
    when(mockUriInfo.getPath()).thenReturn("/path");
    when(mockContext.getProperty(eq(WebAcFilter.SESSION_WEBAC_MODES)))
        .thenReturn(new AuthorizedModes(effectiveAcl, allModes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);

    assertTrue(headers.isEmpty());
    filter.filter(mockContext, mockResponseContext);
    assertFalse(headers.isEmpty());

    final List<Object> links = headers.get("Link");
    assertTrue(links.stream().map(Link.class::cast).anyMatch(link ->
                link.getRels().contains("acl") && "/path?ext=acl".equals(link.getUri().toString())));
    assertTrue(links.stream().map(Link.class::cast).anyMatch(link ->
                "/?ext=acl".equals(link.getUri().toString()) &&
                link.getRels().contains(Trellis.effectiveAcl.getIRIString())));
}
 
Example #19
Source File: PermissionFilterTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
/**
 * API Tests
 */
private ApiEntity initApiMocks() {
    ApiEntity api = new ApiEntity();
    api.setId(API_ID);
    Principal user = () -> USERNAME;
    when(apiService.findById(api.getId())).thenReturn(api);
    when(securityContext.getUserPrincipal()).thenReturn(user);
    Permission perm = mock(Permission.class);
    when(perm.value()).thenReturn(RolePermission.API_ANALYTICS);
    when(perm.acls()).thenReturn(new RolePermissionAction[]{RolePermissionAction.UPDATE});
    when(permissions.value()).thenReturn(new Permission[]{perm});
    UriInfo uriInfo = mock(UriInfo.class);
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.put("api", Collections.singletonList(api.getId()));
    when(uriInfo.getPathParameters()).thenReturn(map);
    when(containerRequestContext.getUriInfo()).thenReturn(uriInfo);
    return api;
}
 
Example #20
Source File: RestUtilsTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    setUpModels();

    expectedJsonld = IOUtils.toString(getClass().getResourceAsStream("/test.json"));
    expectedTypedJsonld = IOUtils.toString(getClass().getResourceAsStream("/test-typed.json"));
    expectedTurtle = IOUtils.toString(getClass().getResourceAsStream("/test.ttl"));
    expectedGroupedTurtle = IOUtils.toString(getClass().getResourceAsStream("/grouped-test.ttl"));
    expectedRdfxml = IOUtils.toString(getClass().getResourceAsStream("/test.xml"));
    expectedGroupedRdfxml = IOUtils.toString(getClass().getResourceAsStream("/grouped-test.xml"));
    expectedTrig= IOUtils.toString(getClass().getResourceAsStream("/test.trig"));

    MockitoAnnotations.initMocks(this);
    when(context.getProperty(AuthenticationProps.USERNAME)).thenReturn("tester");
    when(engineManager.retrieveUser(anyString())).thenReturn(Optional.of(user));
    when(transformer.sesameStatement(any(Statement.class))).thenAnswer(i -> Values.sesameStatement(i.getArgumentAt(0, Statement.class)));
    when(transformer.mobiModel(any(org.eclipse.rdf4j.model.Model.class))).thenReturn(model);
    when(service.skolemize(any(Statement.class))).thenAnswer(i -> i.getArgumentAt(0, Statement.class));
    when(service.deskolemize(model)).thenReturn(model);
    when(uriInfo.getPath(eq(false))).thenReturn("tests");
    when(uriInfo.getBaseUri()).thenReturn(URI.create("urn://test/rest/"));
    when(uriInfo.getAbsolutePath()).thenReturn(URI.create("urn://test/rest/tests"));
    when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<String, String>());
}
 
Example #21
Source File: UserInfoRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Parameters({"userInfoPath"})
@Test
public void requestUserInfoInvalidToken(final String userInfoPath) throws Exception {
    UserInfoRequest userInfoRequest = new UserInfoRequest("INVALID_ACCESS_TOKEN");
    userInfoRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestUserInfoInvalidToken", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #22
Source File: JacksonXMLMessageBodyProviderTest.java    From dropwizard-xml with Apache License 2.0 6 votes vote down vote up
@Test
public void returnsPartialValidatedRequestEntities() throws Exception {
    final Validated valid = Mockito.mock(Validated.class);
    Mockito.doReturn(Validated.class).when(valid).annotationType();
    Mockito.when(valid.value()).thenReturn(new Class[] {Partial1.class, Partial2.class});

    final ByteArrayInputStream entity =
            new ByteArrayInputStream("<PartialExample xmlns=\"\"><id>1</id><text>hello Cemo</text></PartialExample>".getBytes());
    final Class<?> klass = PartialExample.class;

    final Object obj = provider.readFrom((Class<Object>) klass,
            PartialExample.class,
            new Annotation[] {valid},
            MediaType.APPLICATION_XML_TYPE,
            new MultivaluedHashMap<>(),
            entity);

    assertThat(obj)
            .isInstanceOf(PartialExample.class);

    assertThat(((PartialExample) obj).id)
            .isEqualTo(1);
}
 
Example #23
Source File: TestQlikAppMessageBodyGenerator.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testSanitizing() throws Exception {
  QlikAppMessageBodyGenerator generator = new QlikAppMessageBodyGenerator();

  VirtualDataset dataset = new VirtualDataset()
    .setSqlFieldsList(Arrays.asList(new ViewFieldType("testdetail2", "STRUCTURED")));

  DatasetConfig datasetConfig = new DatasetConfig()
    .setName("evil /!@ *-=+{}<>,~ characters")
    .setType(DatasetType.VIRTUAL_DATASET)
    .setFullPathList(DatasetTool.TMP_DATASET_PATH.toPathList())
    .setVirtualDataset(dataset);

  MultivaluedMap<String, Object> httpHeaders = new MultivaluedHashMap<>();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  assertTrue(generator.isWriteable(datasetConfig.getClass(), null, null, WebServer.MediaType.TEXT_PLAIN_QLIK_APP_TYPE));
  generator.writeTo(datasetConfig, DatasetConfig.class, null, new Annotation[] {}, WebServer.MediaType.TEXT_PLAIN_QLIK_APP_TYPE, httpHeaders, baos);

  String script = new String(baos.toByteArray(), UTF_8);

  assertTrue(script.contains("evil_characters: DIRECT QUERY"));
}
 
Example #24
Source File: ApplicationResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected MultivaluedMap<String, String> getRequestParameters() {
    final MultivaluedMap<String, String> entity = new MultivaluedHashMap();

    for (final Map.Entry<String, String[]> entry : httpServletRequest.getParameterMap().entrySet()) {
        if (entry.getValue() == null) {
            entity.add(entry.getKey(), null);
        } else {
            for (final String aValue : entry.getValue()) {
                entity.add(entry.getKey(), aValue);
            }
        }
    }

    return entity;
}
 
Example #25
Source File: ODataExceptionMapperImplTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void dollarFormatXml() throws Exception {
  MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();
  queryParameters.putSingle("$format", "xml");
  when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(queryParameters);

  Response response = exceptionMapper.toResponse(new Exception("text"));
  assertNotNull(response);
  String contentTypeHeader = response.getHeaderString(org.apache.olingo.odata2.api.commons.HttpHeaders.CONTENT_TYPE);
  assertEquals("application/xml", contentTypeHeader);
  String errorMessage = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertXpathExists("/a:error/a:code", errorMessage);
  assertXpathEvaluatesTo("text", "/a:error/a:message", errorMessage);
}
 
Example #26
Source File: ApplicationContextTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void throwsExceptionWhenAsynchronousFeatureIsNotConfiguredButCallerRequestsAsynchronousInvocation() {
    when(request.getRequestUri()).thenReturn(URI.create("http://localhost:8080/a/b?async=true"));
    when(request.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
    when(request.getMethod()).thenReturn("GET");

    thrown.expect(IllegalStateException.class);
    applicationContext.getMethodInvoker(mock(ResourceMethodDescriptor.class));
}
 
Example #27
Source File: DevfileEntityProviderTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldBuildDtoFromValidYaml() throws Exception {

  when(devfileManager.parseYaml(anyString())).thenReturn(new DevfileImpl());

  devfileEntityProvider.readFrom(
      DevfileDto.class,
      DevfileDto.class,
      null,
      MediaType.valueOf("text/x-yaml"),
      new MultivaluedHashMap<>(),
      getClass().getClassLoader().getResourceAsStream("devfile/devfile.yaml"));

  verify(devfileManager).parseYaml(anyString());
}
 
Example #28
Source File: XACMLRequestFilterTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void decisionIsDenyTest() throws Exception {
    when(uriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
    when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(resourceInfo.getResourceMethod()).thenReturn(MockResourceIdStringClass.class.getDeclaredMethod("resourceIdString"));
    when(response.getDecision()).thenReturn(Decision.DENY);
    try {
        filter.filter(context);
        fail("Expected MobiWebException to have been thrown");
    } catch (MobiWebException e) {
        assertEquals("You do not have permission to perform this action", e.getMessage());
        assertEquals(401, e.getResponse().getStatus());
    }
}
 
Example #29
Source File: MoshiMessageBodyReaderTest.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Test public void readsClass() throws IOException {
  Buffer data = new Buffer().writeUtf8("\"hey\"");
  Class<Object> type = (Class) String.class;
  MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
  Object result = reader.readFrom(type, type, new Annotation[0], APPLICATION_JSON_TYPE,
      headers, data.inputStream());
  assertEquals("hey", result);
  assertTrue(headers.isEmpty());
}
 
Example #30
Source File: MoshiMessageBodyReaderTest.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Test public void readDoesNotClose() throws IOException {
  final AtomicBoolean closed = new AtomicBoolean();
  BufferedSource data = Okio.buffer(new ForwardingSource(new Buffer().writeUtf8("\"hey\"")) {
    @Override public void close() throws IOException {
      closed.set(true);
      super.close();
    }
  });
  Class<Object> type = (Class) String.class;
  reader.readFrom(type, type, new Annotation[0], APPLICATION_JSON_TYPE,
      new MultivaluedHashMap<>(), data.inputStream());
  assertFalse(closed.get());
}