use of javax.ws.rs.core.MultivaluedMap in project cxf by apache.
the class JAXRSClientServerBookTest method testGetBookWithCustomHeader.
@Test
public void testGetBookWithCustomHeader() throws Exception {
String endpointAddress = "http://localhost:" + PORT + "/bookstore/books/123";
WebClient wc = WebClient.create(endpointAddress);
Book b = wc.get(Book.class);
assertEquals(123L, b.getId());
MultivaluedMap<String, Object> headers = wc.getResponse().getMetadata();
assertEquals("123", headers.getFirst("BookId"));
assertEquals(MultivaluedMap.class.getName(), headers.getFirst("MAP-NAME"));
assertNotNull(headers.getFirst("Date"));
wc.header("PLAIN-MAP", "true");
b = wc.get(Book.class);
assertEquals(123L, b.getId());
headers = wc.getResponse().getMetadata();
assertEquals("321", headers.getFirst("BookId"));
assertEquals(Map.class.getName(), headers.getFirst("MAP-NAME"));
assertNotNull(headers.getFirst("Date"));
}
use of javax.ws.rs.core.MultivaluedMap in project openremote by openremote.
the class QueryParameterInjectorFilter method filter.
@SuppressWarnings("unchecked")
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
MultivaluedMap<String, String> queryParameters = (MultivaluedMap<String, String>) requestContext.getProperty(QUERY_PARAMETERS_PROPERTY);
String dynamicValue = requestContext.getProperty(DYNAMIC_VALUE_PROPERTY) != null ? (String) requestContext.getProperty(DYNAMIC_VALUE_PROPERTY) : "";
if (queryParameters == null) {
return;
}
UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
queryParameters.forEach((name, values) -> {
Object[] formattedValues = values.stream().map(v -> {
v = v.replaceAll(Protocol.DYNAMIC_VALUE_PLACEHOLDER_REGEXP, dynamicValue);
Matcher matcher = DYNAMIC_TIME_PATTERN.matcher(v);
if (matcher.find()) {
long millisToAdd = 0L;
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
if (matcher.groupCount() > 0) {
dateTimeFormatter = DateTimeFormatter.ofPattern(matcher.group(1));
}
if (matcher.groupCount() == 2) {
millisToAdd = Long.parseLong(matcher.group(2));
}
v = v.replaceAll(Protocol.DYNAMIC_TIME_PLACEHOLDER_REGEXP, dateTimeFormatter.format(Instant.now().plusMillis(millisToAdd).atZone(ZoneId.systemDefault())));
}
return v;
}).toArray();
uriBuilder.queryParam(name, formattedValues);
});
requestContext.setUri(uriBuilder.build());
}
use of javax.ws.rs.core.MultivaluedMap in project kylo by Teradata.
the class AlertsController method createCriteria.
private AlertCriteria createCriteria(UriInfo uriInfo) {
// Query params: limit, state, level, before-time, after-time, before-alert, after-alert
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
AlertCriteria criteria = provider.criteria();
try {
Optional.ofNullable(params.get("type")).ifPresent(list -> list.forEach(typeStr -> criteria.type(URI.create(typeStr))));
Optional.ofNullable(params.get("subtype")).ifPresent(list -> list.forEach(subtype -> criteria.subtype(subtype)));
Optional.ofNullable(params.get("limit")).ifPresent(list -> list.forEach(limitStr -> criteria.limit(Integer.parseInt(limitStr))));
Optional.ofNullable(params.get("state")).ifPresent(list -> list.forEach(stateStr -> criteria.state(Alert.State.valueOf(stateStr.toUpperCase()))));
Optional.ofNullable(params.get("level")).ifPresent(list -> list.forEach(levelStr -> criteria.level(Alert.Level.valueOf(levelStr.toUpperCase()))));
Optional.ofNullable(params.get("before")).ifPresent(list -> list.forEach(timeStr -> criteria.before(Formatters.parseDateTime(timeStr))));
Optional.ofNullable(params.get("after")).ifPresent(list -> list.forEach(timeStr -> criteria.after(Formatters.parseDateTime(timeStr))));
return criteria;
} catch (IllegalArgumentException e) {
throw new WebApplicationException("Invalid query parameter: " + e.getMessage(), Status.BAD_REQUEST);
}
}
use of javax.ws.rs.core.MultivaluedMap in project airlift by airlift.
the class JaxrsTestingHttpProcessor method handle.
@Override
public Response handle(Request request) throws Exception {
// prepare request to jax-rs resource
MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<>();
for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
requestHeaders.add(entry.getKey(), entry.getValue());
}
Invocation.Builder invocationBuilder = client.target(request.getUri()).request().headers(requestHeaders);
Invocation invocation;
if (request.getBodyGenerator() == null) {
invocation = invocationBuilder.build(request.getMethod());
} else {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
request.getBodyGenerator().write(byteArrayOutputStream);
byteArrayOutputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
Entity<byte[]> entity = Entity.entity(bytes, (String) requestHeaders.get("Content-Type").stream().collect(onlyElement()));
invocation = invocationBuilder.build(request.getMethod(), entity);
}
// issue request, and handle exceptions
javax.ws.rs.core.Response result;
try {
result = invocation.invoke(javax.ws.rs.core.Response.class);
} catch (ProcessingException exception) {
if (trace) {
log.warn(exception.getCause(), "%-8s %s -> Exception", request.getMethod(), request.getUri());
}
// to facilitate testing exceptional paths
if (exception.getCause() instanceof Exception) {
throw (Exception) exception.getCause();
}
throw exception;
} catch (Throwable throwable) {
if (trace) {
log.warn(throwable, "%-8s %s -> Fail", request.getMethod(), request.getUri());
}
throw throwable;
}
// process response from jax-rs resource
ImmutableListMultimap.Builder<String, String> responseHeaders = ImmutableListMultimap.builder();
for (Map.Entry<String, List<String>> headerEntry : result.getStringHeaders().entrySet()) {
for (String value : headerEntry.getValue()) {
responseHeaders.put(headerEntry.getKey(), value);
}
}
if (trace) {
log.warn("%-8s %s -> OK", request.getMethod(), request.getUri());
}
return new TestingResponse(HttpStatus.fromStatusCode(result.getStatus()), responseHeaders.build(), result.readEntity(byte[].class));
}
use of javax.ws.rs.core.MultivaluedMap in project kie-wb-common by kiegroup.
the class MavenRestClientTest method postTest.
@Test
public void postTest() {
try {
fileSystemTestingUtils.setup();
ioService = fileSystemTestingUtils.getIoService();
final String repoName = "myrepo";
final JGitFileSystem fs = (JGitFileSystem) ioService.newFileSystem(URI.create("git://" + repoName), new HashMap<String, Object>() {
{
put("init", Boolean.TRUE);
put("internal", Boolean.TRUE);
}
});
ioService.startBatch(fs);
String pom = "target/test-classes/kjar-2-single-resources/pom.xml";
if (!runIntoMavenCLI) {
pom = "kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-distribution/target/test-classes/kjar-2-single-resources/pom.xml";
}
ioService.write(fs.getPath("/kjar-2-single-resources/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File(pom).toPath())));
String personDotJava = "target/test-classes/kjar-2-single-resources/src/main/java/org/kie/maven/plugin/test/Person.java";
if (!runIntoMavenCLI) {
personDotJava = "kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-distribution/target/test-classes/kjar-2-single-resources/src/main/java/org/kie/maven/plugin/test/Person.java";
}
ioService.write(fs.getPath("/kjar-2-single-resources/src/main/java/org/kie/maven/plugin/test/Person.java"), new String(java.nio.file.Files.readAllBytes(new File(personDotJava).toPath())));
String simpleRulesDotDRL = "target/test-classes/kjar-2-single-resources/src/main/resources/AllResourcesTypes/simple-rules.drl";
if (!runIntoMavenCLI) {
simpleRulesDotDRL = "kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-distribution/target/test-classes/kjar-2-single-resources/src/main/resources/AllResourceTypes/simple-rules.drl";
}
ioService.write(fs.getPath("/kjar-2-single-resources/src/main/resources/AllResourcesTypes/simple-rules.drl"), new String(java.nio.file.Files.readAllBytes(new File(simpleRulesDotDRL).toPath())));
String kmodule = "target/test-classes/kjar-2-single-resources/src/main/resources/META-INF/kmodule.xml";
if (!runIntoMavenCLI) {
kmodule = "kie-wb-common-services/kie-wb-common-compiler/kie-wb-common-compiler-distribution/target/test-classes/kjar-2-single-resources/src/main/resources/META-INF/kmodule.xml";
}
ioService.write(fs.getPath("/kjar-2-single-resources/src/main/resources/META-INF/kmodule.xml"), new String(java.nio.file.Files.readAllBytes(new File(kmodule).toPath())));
ioService.endBatch();
Path tmpRootCloned = Files.createTempDirectory("cloned");
Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), "dummy"));
final File gitClonedFolder = new File(tmpCloned.toFile(), ".clone.git");
final Git cloned = Git.cloneRepository().setURI(fs.getGit().getRepository().getDirectory().toURI().toString()).setBare(false).setDirectory(gitClonedFolder).call();
assertThat(cloned).isNotNull();
mavenRepoPath = Paths.get(System.getProperty("user.home"), ".m2", "repository");
tmpRoot = Paths.get(gitClonedFolder + "/dummy/");
Client client = ClientBuilder.newClient();
WebTarget target = client.target(deploymentUrl.toString() + "rest/maven/");
MultivaluedMap headersMap = new MultivaluedHashMap();
headersMap.add("project", tmpRoot.toAbsolutePath().toString() + "/dummy");
headersMap.add("mavenrepo", mavenRepoPath.toAbsolutePath().toString());
headersMap.add("settings_xml", mavenSettingsPath);
Future<Response> responseFuture = target.request().headers(headersMap).async().post(Entity.entity(String.class, MediaType.TEXT_PLAIN));
Response response = responseFuture.get();
assertThat(response.getStatusInfo().getStatusCode()).isEqualTo(200);
InputStream is = response.readEntity(InputStream.class);
byte[] serializedCompilationResponse = IOUtils.toByteArray(is);
HttpCompilationResponse res = RestUtils.readDefaultCompilationResponseFromBytes(serializedCompilationResponse);
assertThat(res).isNotNull();
assertThat(res.getDependencies()).hasSize(4);
assertThat(res.getTargetContent()).hasSize(3);
tearDown();
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
fileSystemTestingUtils.cleanup();
}
}
Aggregations