@Test public void testAuthFilter() throws IOException { final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); when(mockContext.getHeaders()).thenReturn(headers); final AuthFilter<String, Principal> filter = new AnonymousAuthFilter.Builder() .setAuthenticator(new AnonymousAuthenticator()).buildAuthFilter(); filter.filter(mockContext); verify(mockContext).setSecurityContext(securityCaptor.capture()); assertEquals(Trellis.AnonymousAgent.getIRIString(), securityCaptor.getValue().getUserPrincipal().getName()); assertFalse(securityCaptor.getValue().isUserInRole("role")); assertFalse(securityCaptor.getValue().isSecure()); assertEquals("NONE", securityCaptor.getValue().getAuthenticationScheme()); }
@Test public void testFindFixedVariable() throws MappingException { Mapping mapping1 = new Mapping("/fixed/{variable: [a-zA-Z]+}", null); Mapping mapping2 = new Mapping("/fixed/{variable: \\d+}", null); MappingTree mappingTree = new MappingTree(); mappingTree.put(mapping1); mappingTree.put(mapping2); MultivaluedHashMap<String,String> pathVariables1 = new MultivaluedHashMap<String,String>(); MultivaluedHashMap<String,String> pathVariables2 = new MultivaluedHashMap<String,String>(); Mapping find1 = mappingTree.find("fixed/aaa", pathVariables1); Mapping find2 = mappingTree.find("fixed/123", pathVariables2); Mapping find3 = mappingTree.find("fixed/"); Mapping find4 = mappingTree.find("fixed"); assertEquals(mapping1, find1); assertEquals(mapping2, find2); assertNull(find3); assertNull(find4); assertEquals(true, pathVariables1.containsKey("variable")); assertEquals(true, pathVariables2.containsKey("variable")); assertEquals(1, pathVariables1.get("variable").size()); assertEquals(1, pathVariables2.get("variable").size()); assertEquals("aaa", pathVariables1.get("variable").get(0)); assertEquals("123", pathVariables2.get("variable").get(0)); }
public MinijaxHttpHeaders(final HttpServletRequest request) { headers = new MultivaluedHashMap<>(); final Enumeration<String> ne = request.getHeaderNames(); while (ne.hasMoreElements()) { final String name = ne.nextElement(); final Enumeration<String> ve = request.getHeaders(name); while (ve.hasMoreElements()) { headers.add(name, ve.nextElement()); } } cookies = CookieUtils.convertServletToJax(request.getCookies()); }
/** * Change a broker Instance * * @param brokerName * @throws CloudKarafkaServiceException */ public void changeInstance(final String instanseId, final String brokerName, final String plan) throws CloudKarafkaServiceException { // build input form final MultivaluedMap<String, String> form = new MultivaluedHashMap<>(); form.add("name", brokerName); form.add("plan", plan); //build post request final String target = String.format("%s/%s/%s", brokerConfig.getCloudkarafkaApiUrl(), "instances",instanseId); final WebTarget webTarget = client.target(target); // call create broker instances API webTarget.request(MediaType.APPLICATION_JSON).put(Entity.form(form)); }
@Test public void mapResponse_withHeaders() { MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); headers.add("h", "v"); new Expectations() { { jaxrsResponse.getStatusInfo(); result = Status.OK; jaxrsResponse.getEntity(); result = "result"; jaxrsResponse.getHeaders(); result = headers; } }; Response response = mapper.mapResponse(null, jaxrsResponse); Assert.assertEquals(Status.OK, response.getStatus()); Assert.assertEquals("result", response.getResult()); Assert.assertEquals(1, response.getHeaders().getHeaderMap().size()); Assert.assertThat(response.getHeaders().getHeader("h"), Matchers.contains("v")); }
private MultivaluedMap<String,String> getValidSessionParamsWithHetu() { MultivaluedMap<String,String> sessionParams = new MultivaluedHashMap<>(); sessionParams.putSingle("token", "token"); sessionParams.putSingle("B02K_VERS", "0002"); sessionParams.putSingle("B02K_TIMESTMP", "000" + bankReady.instant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+"000000"); sessionParams.putSingle("B02K_IDNBR", "0000000000"); sessionParams.putSingle("B02K_STAMP", VALID_IDENTIFIER); sessionParams.putSingle("B02K_CUSTNAME", "CUSTNAME"); sessionParams.putSingle("B02K_KEYVERS", "0001"); sessionParams.putSingle("B02K_ALG", "03"); sessionParams.putSingle("B02K_CUSTID", "210280-928R"); sessionParams.putSingle("B02K_CUSTTYPE", "01"); sessionParams.putSingle("B02K_MAC", "1D609B7B2CAF04AF1C50C7C7A04FBE081E77566C7BDB023F26EB2739C63718E0"); return sessionParams; }
@SuppressWarnings("rawtypes") @Test public void filter404NoParameter() { final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class); final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class); Mockito.when(responseContext.getStatus()).thenReturn(204); final Annotation anno1 = Mockito.mock(Annotation.class); final Annotation anno2 = Mockito.mock(Annotation.class); final Annotation[] annotations = new Annotation[] { anno1, anno2 }; Mockito.when((Class) anno2.annotationType()).thenReturn(OnNullReturn404.class); Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations); final UriInfo uriInfo = Mockito.mock(UriInfo.class); final MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>(); Mockito.when(uriInfo.getPathParameters()).thenReturn(parameters); Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo); filter.filter(requestContext, responseContext); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()).setStatus(404); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()) .setEntity("{\"code\":\"data\",\"message\":null,\"parameters\":null,\"cause\":null}", annotations, MediaType.APPLICATION_JSON_TYPE); }
@SuppressWarnings("rawtypes") @Test public void filter404SingleParameter() { final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class); final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class); Mockito.when(responseContext.getStatus()).thenReturn(204); final Annotation anno1 = Mockito.mock(Annotation.class); final Annotation anno2 = Mockito.mock(Annotation.class); final Annotation[] annotations = new Annotation[] { anno1, anno2 }; Mockito.when((Class) anno2.annotationType()).thenReturn(OnNullReturn404.class); Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations); final UriInfo uriInfo = Mockito.mock(UriInfo.class); final MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>(); parameters.putSingle("id", "2000"); Mockito.when(uriInfo.getPathParameters()).thenReturn(parameters); Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo); filter.filter(requestContext, responseContext); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()).setStatus(404); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()).setEntity( "{\"code\":\"entity\",\"message\":\"2000\",\"parameters\":null,\"cause\":null}", annotations, MediaType.APPLICATION_JSON_TYPE); }
@Test public void testAcceptableLanguages() throws IOException { final MultivaluedMap<String, String> mockHeaders = new MultivaluedHashMap<>(); mockHeaders.add("Accept-Language", "en-US"); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", URI.create("/"), mockHeaders, null, null); try (final MinijaxRequestContext context = new MinijaxRequestContext(null, mockRequest, null)) { final List<Locale> locales = context.getAcceptableLanguages(); assertEquals(1, locales.size()); assertEquals("en-US", locales.get(0).toLanguageTag()); // Assert that same cached object assertTrue(locales == context.getAcceptableLanguages()); } }
@Test public void testQuoteInPathAndDatasetName() throws Exception { QlikAppMessageBodyGenerator generator = new QlikAppMessageBodyGenerator(); VirtualDataset dataset = new VirtualDataset() .setSqlFieldsList(Arrays.asList(new ViewFieldType("test dimension", "VARCHAR"), new ViewFieldType("test \" measure", "INTEGER"))); DatasetConfig datasetConfig = new DatasetConfig() .setName("UNTITLED") .setType(DatasetType.VIRTUAL_DATASET) .setFullPathList(Arrays.asList("@dremio", "fol\"der.ext", "foo", "bar")) .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); // make sure everything is escaped correctly assertTrue(script.contains(" DIMENSION \"test dimension\"")); assertTrue(script.contains(" MEASURE \"test \"\" measure\"")); assertTrue(script.contains(" FROM \"@dremio\".\"fol\"\"der.ext\".\"foo\".\"bar\"")); }
@Test public void testPost() throws Exception { MockRepresentation content = new MockRepresentation(); content.setId(1L); MockRequestParameters params = new MockRequestParameters(); params.setId(1L); UriInfo uriinfo = mock(UriInfo.class); MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); map.putSingle(CommonParams.PARAM_VERSION, "v" + Integer.valueOf(CommonParams.VERSION_1).toString()); Mockito.when(uriinfo.getPathParameters()).thenReturn(map); Response response = post(uriinfo, backendPost, content, params); assertEquals(Status.CREATED.getStatusCode(), response.getStatus()); }
@Test public void testPutWithETag() throws Exception { MockRepresentation content = new MockRepresentation(); content.setId(1L); content.setETag(1L); MockRequestParameters params = new MockRequestParameters(); params.setId(1L); params.setMatch("1"); UriInfo uriinfo = mock(UriInfo.class); MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); map.putSingle(CommonParams.PARAM_VERSION, "v" + Integer.valueOf(CommonParams.VERSION_1).toString()); Mockito.when(uriinfo.getPathParameters()).thenReturn(map); Response response = put(uriinfo, backendPutETag, content, params); assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus()); }
@SuppressWarnings("boxing") private MultivaluedMap<String, String> testVersionFilter(String version) throws WebApplicationException, NoSuchMethodException { ResourceInfo resourceInfo = mock(ResourceInfo.class); ContainerRequestContext request = mock(ContainerRequestContext.class); UriInfo uriInfo = mock(UriInfo.class); when(request.getUriInfo()).thenReturn(uriInfo); Method method = SinceClass.class.getMethod("dummy"); MultivaluedMap<String, String> prop = new MultivaluedHashMap<>(); prop.putSingle(CommonParams.PARAM_VERSION, version); when(uriInfo.getPathParameters()).thenReturn(prop); VersionFilter filter = spy(new VersionFilter()); when(filter.getResourceInfo()).thenReturn(resourceInfo); when(resourceInfo.getResourceMethod()).thenReturn(method); filter.filter(request); return prop; }
@SuppressWarnings("boxing") @Test public void testVersionFilterVersionNotExisting() { try { UriInfo info = mock(UriInfo.class); MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); ContainerRequestContext request = mock( ContainerRequestContext.class); when(info.getPathParameters()).thenReturn(map); when(request.getUriInfo()).thenReturn(info); VersionFilter filter = new VersionFilter(); filter.filter(request); } catch (WebApplicationException e) { assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus()); } }
@Test public void testQuoting() throws Exception { QlikAppMessageBodyGenerator generator = new QlikAppMessageBodyGenerator(); VirtualDataset dataset = new VirtualDataset() .setSqlFieldsList(Arrays.asList(new ViewFieldType("testdimension", "VARCHAR"), new ViewFieldType("testmeasure", "INTEGER"))); DatasetConfig datasetConfig = new DatasetConfig() .setName("UNTITLED") .setType(DatasetType.VIRTUAL_DATASET) .setFullPathList(Arrays.asList("space", "folder.ext", "UNTITLED")) .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(" DIMENSION \"testdimension\"")); assertTrue(script.contains(" MEASURE \"testmeasure\"")); assertTrue(script.contains(" FROM \"space\".\"folder.ext\".\"UNTITLED\"")); }
/** Retrieve a generic list containing a value/stationcount mapping. * @param subpath the API sub path to use for the call. * @return map of value and stationcount pairs. * */ private Map<String, Integer> retrieveValueStationCountList( final String subpath) { MultivaluedMap<String, String> requestParams = new MultivaluedHashMap<>(); Entity entity = Entity.form(requestParams); Response response = null; try { response = builder(webTarget.path(subpath)) .post(entity); List<Map<String, String>> map = response.readEntity( new GenericType<List<Map<String, String>>>() { }); checkResponseStatus(response); return map.stream() .collect(Collectors.toMap( m -> m.get("value"), m -> Integer.parseInt(m.get("stationcount")))); } finally { close(response); } }
/** Get a list of all stations on a certain API path. * @param paging the offset and limit of the page to retrieve. * @param path the path to retrieve, for example "json/stations". * @param listParam the optional listing parameters. * @return the partial list of the stations. Can be empty for exceeding the * possible stations. */ private List<Station> listStationsPath(final Optional<Paging> paging, final String path, final ListParameter...listParam) { MultivaluedMap<String, String> requestParams = new MultivaluedHashMap<>(); paging.ifPresent(p -> applyPaging(p, requestParams)); Arrays.stream(listParam).forEach(lp -> lp.applyTo(requestParams)); Entity entity = Entity.form(requestParams); Response response = null; try { response = builder(webTarget.path(path)) .post(entity); checkResponseStatus(response); return response.readEntity(new GenericType<List<Station>>() { }); } finally { close(response); } }
@Before public void setUp() { SimpleValueFactory valueFactory = SimpleValueFactory.getInstance(); parameter = new StringTermParameter(valueFactory.createIRI("http://parameter-iri"), "parameter-name", true); parameter2 = new StringTermParameter(valueFactory.createIRI("http://parameter2-iri"), "parameter2-name", true); product = new TestInformationProduct(DBEERPEDIA.ORIGIN_INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES_LABEL.stringValue(), ResultType.GRAPH, ImmutableList.of(parameter, parameter2), templateProcessorMock); mapper = new RequestParameterMapper(); requestParameters = new RequestParameters(); MultivaluedMap<String, String> mvMap = new MultivaluedHashMap<>(); mvMap.put("param1", ImmutableList.of("value", "valueB")); mvMap.put("param2", ImmutableList.of("value2")); requestParameters.putAll(mvMap); }
@Test public void map_ReturnsCorrectParameterName_ForQueryParameter() { // Arrange QueryParameter queryParameter = new QueryParameter(); queryParameter.setName("param1"); queryParameter.setIn("query"); queryParameter.setVendorExtension(OpenApiSpecificationExtensions.PARAMETER, parameter.getIdentifier().stringValue()); Operation operation = new Operation(); operation.addParameter(queryParameter); MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>(); queryParameters.put(queryParameter.getName(), ImmutableList.of("value", "valueB")); // Act Map<String, String> result = mapper.map(operation, product, requestParameters); // Assert assertThat(result.size(), is(1)); assertThat(result, hasEntry(parameter.getName(), "value")); }
@Test public void map_ReturnsCorrectParameterName_ForHeaderParameter() { // Arrange HeaderParameter headerParameter = new HeaderParameter(); headerParameter.setName("param1"); headerParameter.setIn("header"); headerParameter.setVendorExtension(OpenApiSpecificationExtensions.PARAMETER, parameter.getIdentifier().stringValue()); Operation operation = new Operation(); operation.addParameter(headerParameter); MultivaluedMap<String, String> headerParameters = new MultivaluedHashMap<>(); headerParameters.put(headerParameter.getName(), ImmutableList.of("value", "valueB")); // Act Map<String, String> result = mapper.map(operation, product, requestParameters); // Assert assertThat(result.size(), is(1)); assertThat(result, hasEntry(parameter.getName(), "value")); }
public <T> T generateClient(Class<T> resource) { Client clientToUse = client != null ? client : ClientBuilder.newClient(); MultivaluedMap<String, Object> headerArg = new MultivaluedHashMap<>(headers); WebTarget webTarget = clientToUse.target(uri); if (apiPath != null) { webTarget = webTarget.path(apiPath); } if(throwExceptionForErrors) { webTarget.register(ClientErrorResponseFilter.class); } webTarget.register(RequestIdClientFilter.class); webTarget.register(ClientNameFilter.class); if (logging) { webTarget.register(ClientLogFilter.class); } return WebResourceFactory.newResource(resource, webTarget, false, headerArg, cookies, new Form()); }
@Test public void testFieldNamesWithSpaceQuoting() throws Exception { QlikAppMessageBodyGenerator generator = new QlikAppMessageBodyGenerator(); VirtualDataset dataset = new VirtualDataset() .setSqlFieldsList(Arrays.asList(new ViewFieldType("test dimension", "VARCHAR"), new ViewFieldType("test \" measure", "INTEGER"))); DatasetConfig datasetConfig = new DatasetConfig() .setName("UNTITLED") .setType(DatasetType.VIRTUAL_DATASET) .setFullPathList(Arrays.asList("space", "folder.ext", "UNTITLED")) .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); // make sure everything is escaped correctly assertTrue(script.contains(" DIMENSION \"test dimension\"")); assertTrue(script.contains(" MEASURE \"test \"\" measure\"")); assertTrue(script.contains(" FROM \"space\".\"folder.ext\".\"UNTITLED\"")); }
@Test public void map_ReturnsRequiredParameter_WithValidData() { // Arrange MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>(); // Note there are multiple values for this parameter, to test that the first value is used only queryParameters.put(requiredParameter.getName(), ImmutableList.of("value", "valueB")); when(uriInfoMock.getQueryParameters()).thenReturn(queryParameters); // Act Map<String, String> result = representationRequestParameterMapper.map(product, contextMock); // Assert assertThat(result.size(), is(1)); assertThat(result, hasEntry(requiredParameter.getName(), "value")); }
@Test public void map_ReturnsOptionalParameter_WithValidData() { // Arrange MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>(); // Note there are multiple values for this parameter, to test that the first value is used only queryParameters.put(optionalParameter.getName(), ImmutableList.of("value", "valueB")); when(uriInfoMock.getQueryParameters()).thenReturn(queryParameters); // Act Map<String, String> result = representationRequestParameterMapper.map(product, contextMock); // Assert assertThat(result.size(), is(1)); assertThat(result, hasEntry(optionalParameter.getName(), "value")); }
@Test public void map_ReturnsParameters_WithMultipleParameters() { // Arrange MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>(); // Note there are multiple values for this parameter, to test that the first value is used only queryParameters.put(requiredParameter.getName(), ImmutableList.of("value", "valueB")); queryParameters.put(optionalParameter.getName(), ImmutableList.of("value2")); when(uriInfoMock.getQueryParameters()).thenReturn(queryParameters); // Act Map<String, String> result = representationRequestParameterMapper.map(product, contextMock); // Assert assertThat(result.size(), is(2)); assertThat(result, hasEntry(requiredParameter.getName(), "value")); assertThat(result, hasEntry(optionalParameter.getName(), "value2")); }
@Test public void testAcceptableMediaTypes() throws IOException { final MultivaluedMap<String, String> mockHeaders = new MultivaluedHashMap<>(); mockHeaders.add("Accept", "text/plain"); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", URI.create("/"), mockHeaders, null, null); try (final MinijaxRequestContext context = new MinijaxRequestContext(null, mockRequest, null)) { final List<MediaType> mediaTypes = context.getAcceptableMediaTypes(); assertEquals(1, mediaTypes.size()); assertEquals("text/plain", mediaTypes.get(0).toString()); // Assert that same cached object assertTrue(mediaTypes == context.getAcceptableMediaTypes()); } }
private String getResponseUrlById(int testCaseId, String samlRequest) { Response complianceToolSsoResponse = client .target(SSO_LOCATION) .request() .buildPost(form(new MultivaluedHashMap<>(ImmutableMap.of("SAMLRequest", samlRequest)))) .invoke(); JSONObject complianceToolResponseBody = new JSONObject(complianceToolSsoResponse.readEntity(String.class)); Response complianceToolScenariosResponse = client .target(complianceToolResponseBody.getString("responseGeneratorLocation")) .request() .buildGet() .invoke(); JSONObject complianceToolScenarios = new JSONObject(complianceToolScenariosResponse.readEntity(String.class)); for (Object object : complianceToolScenarios.getJSONArray("testCases")) { JSONObject jsonObject = (JSONObject) object; int id = jsonObject.getInt("id"); if (id == testCaseId) { return jsonObject.getString("executeUri"); } } throw new RuntimeException("Couldn't find a test case with id + " + testCaseId); }
@Test public void testMultipartForm() throws IOException { final MultivaluedMap<String, String> mockHeaders = new MultivaluedHashMap<>(); mockHeaders.add("Content-Type", "multipart/form-data"); final String mockContent = "------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" + "Content-Disposition: form-data; name=\"a\"\n" + "\n" + "b\n" + "------WebKitFormBoundarycTqA2AimXQHBAJbZ"; final ByteArrayInputStream mockContentBody = new ByteArrayInputStream(mockContent.getBytes(StandardCharsets.UTF_8)); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", URI.create("/"), mockHeaders, mockContentBody, null); try (final MinijaxRequestContext context = new MinijaxRequestContext(null, mockRequest, null)) { final MinijaxForm form = context.getForm(); assertTrue(form instanceof MinijaxMultipartForm); assertEquals("b", form.getString("a")); // Assert that same cached object assertTrue(form == context.getForm()); } }
@Override public Form asForm() { final MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); for (final Part part : values.values()) { if (part.getSubmittedFileName() != null) { continue; } try { map.add(part.getName(), IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } return new Form(map); }
/** * Decodes a URL-encoded string into key-value pairs. * * @param str The input string. * @return The key-value pairs. */ public static MultivaluedMap<String, String> urlDecodeMultivaluedParams(final String str) { final MultivaluedMap<String, String> fields = new MultivaluedHashMap<>(); if (str == null || str.isEmpty()) { return fields; } final String[] pairs = str.split("&"); for (int i = 0; i < pairs.length; i++) { final String[] keyValue = pairs[i].split("="); final String key = keyValue[0]; final String value = keyValue.length > 1 ? keyValue[1] : null; fields.add(urlDecode(key), urlDecode(value)); } return fields; }
/** * Generate parameters required for initial token grant. */ @Nonnull private MultivaluedMap<String, String> grantTokenParameters() { final MultivaluedHashMap<String, String> results = initParameters(); results.put( OAuth2Constants.GRANT_TYPE, Collections.singletonList( _config.getGrantType() ) ); results.put( "username", Collections.singletonList( _config.getUsername() ) ); results.put( "password", Collections.singletonList( _config.getPassword() ) ); return results; }
/** * Initialize parameters, ensuring clientID is set if required. */ @Nonnull private MultivaluedHashMap<String, String> initParameters() { final MultivaluedHashMap<String, String> results = new MultivaluedHashMap<>(); if ( _config.isPublicClient() ) { results.put( OAuth2Constants.CLIENT_ID, Collections.singletonList( _config.getClientID() ) ); } return results; }
private String requestAccessToken(final String username) throws UnsupportedEncodingException { WebTarget oauth2Service = ClientBuilder.newClient().register(JacksonJaxbJsonProvider.class).target("http://localhost:7001/security"); MultivaluedMap<String, String> request = new MultivaluedHashMap<>(); request.putSingle("grant_type", "client_credentials"); String credentials = Base64.getEncoder().encodeToString((username + ":passw0rd").getBytes("UTF-8")); Map<String, String> oauthResponse = oauth2Service.path("oauth2/token") .request(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .header("Authorization", "Basic " + credentials) .header("X-Log-Token", DiagnosticContext.getLogToken()) .header("X-Service-Generation", "1") .header("X-Client-Version", "1.0.0") .post(Entity.form(request), Map.class); return oauthResponse.get("access_token"); }
@Test public void testJSONGeneratorConfigured() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http://localhost/foo/bar?pretty", "GET").accept("random/media").build(); ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNotNull(modifier); JsonGenerator g = mock(JsonGenerator.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), mock(ObjectWriter.class), g); verify(g).useDefaultPrettyPrinter(); }
public static MultivaluedHashMap<String, String> headers() { MultivaluedHashMap<String, String> headerValues = new MultivaluedHashMap<>(); headerValues.add("User-Agent", "Postmark Java Library: " + libraryVersion()); headerValues.add("Accept", "application/json"); headerValues.add("Content-Type", "application/json"); return headerValues; }
@Test void execute() throws IOException, PostmarkException { HttpClient client = new HttpClient(new MultivaluedHashMap<>()); HttpClient.ClientResponse response = client.execute(HttpClient.REQUEST_TYPES.GET, "https://" + Postmark.DEFAULTS.API_URL.value); assertEquals(response.getCode(),302); assertNotNull(response.getMessage()); }
@Test public void testGeneratedOutput() throws Exception { QlikAppMessageBodyGenerator generator = new QlikAppMessageBodyGenerator(); VirtualDataset dataset = new VirtualDataset() .setSqlFieldsList(Arrays.asList( new ViewFieldType("testdimension", "VARCHAR"), new ViewFieldType("testdimension2", "CHAR"), new ViewFieldType("testmeasure", "INTEGER"), new ViewFieldType("testmeasure2", "REAL"), new ViewFieldType("testdetail", "MAP"), new ViewFieldType("testdetail2", "STRUCTURED"))); DatasetConfig datasetConfig = new DatasetConfig() .setName("UNTITLED") .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(" DIMENSION \"testdimension\", \"testdimension2\"")); assertTrue(script.contains(" MEASURE \"testmeasure\", \"testmeasure2\"")); assertTrue(script.contains(" DETAIL \"testdetail\", \"testdetail2\"")); assertTrue(script.contains(" FROM \"tmp\".\"UNTITLED\"")); }
@Test public void testHeaders() throws IOException { final MultivaluedMap<String, String> mockHeaders = new MultivaluedHashMap<>(); mockHeaders.add("a", "b"); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", URI.create("/"), mockHeaders, null, null); try (final MinijaxRequestContext context = new MinijaxRequestContext(null, mockRequest, null)) { final MultivaluedMap<String, String> headers = context.getHeaders(); assertEquals("b", headers.get("a").get(0)); // Assert that same cached object assertTrue(headers == context.getHeaders()); } }
@Scheduled(cron = "0 0 17 * * ?") // second, minute, hour, day of month, month, day(s) of week (UTC on K8s) public void cleanDeployments() { List<String> clusters = new ArrayList<>(); // Add clusters that need to be cleaned clusters.add("sandbox-cluster"); clusters.add("dev-int-cluster"); for (int i = 0; i < clusters.size(); i++) { String cluster = clusters.get(i); ResourceList<DeploymentResource> deploymentResourceList = deploymentResourceService.getAllDeployments(cluster); List<DeploymentResource> deployments = mapper.convertValue(deploymentResourceList.getItems(), new TypeReference<List<DeploymentResource>>() {}); for (DeploymentResource deployment : deployments) { Map<String, String> matchLabels = deployment.getSpec().getSelector().getMatchLabels(); MultivaluedMap<String, String> selector = new MultivaluedHashMap<>(); String namespace = deployment.getMetadata().getNamespace(); String name = deployment.getMetadata().getName(); for (Entry<String, String> entry : matchLabels.entrySet()) { selector.add(entry.getKey(), entry.getValue()); } PodList podList = podService.getPodsByLabels(cluster, namespace, selector); iteratePods(podList, deployment, cluster, namespace, name); } } }
private void initializeTupasIdentification(HttpServletRequest request, HttpServletResponse response) throws ExternalAuthenticationException, IOException { String convKey = ExternalAuthentication.startExternalAuthentication(request); /* The above method enriches the servlet request with Shibboleth IdP related * data such as the relying party value which is fetched in the code below. * Note that this data is not fetched from browser generated request but directly * from Shibboleth through internal class method call */ HttpSession session = request.getSession(); if (session == null) { response.sendRedirect(createErrorURL(errorParamIdpExt)); return; } String sessionId = session.getId(); String relyingParty = String.valueOf(request.getAttribute(ExternalAuthentication.RELYING_PARTY_PARAM)); // Relying party parameter must match the allowed entity ID format if (!UrlParamService.isValidEntityId(relyingParty)) { logger.warn("<<{}>> Received invalid relying party"); response.sendRedirect(createErrorURL(errorParamInvalidEID)); return; } else { ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(convKey, request); AuthenticationContext ac = prc.getSubcontext(AuthenticationContext.class); if ( ac == null ) { logger.info("No AuthenticationContext"); response.sendRedirect(createErrorURL(errorParamIdpExt)); return; } MultivaluedMap<String, String> requestParams = new MultivaluedHashMap<>(); requestParams.putSingle("declRef", resolveDeclarationRef(prc)); requestParams.putSingle("lang", resolveLanguage(prc)); requestParams.putSingle("ckey", convKey); requestParams.putSingle("sessionId", sessionId); String initResult = authenticationHandlerService.initializeSession(requestParams); response.getWriter().println(initResult); return; } }