Search in sources :

Example 71 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project cxf by apache.

the class SamlFormOutInterceptor method getRequestForm.

@SuppressWarnings("unchecked")
protected Form getRequestForm(Message message) {
    Object ct = message.get(Message.CONTENT_TYPE);
    if (ct == null || !MediaType.APPLICATION_FORM_URLENCODED.equalsIgnoreCase(ct.toString())) {
        return null;
    }
    MessageContentsList objs = MessageContentsList.getContentsList(message);
    if (objs != null && objs.size() == 1) {
        Object obj = objs.get(0);
        if (obj instanceof Form) {
            return (Form) obj;
        } else if (obj instanceof MultivaluedMap) {
            return new Form((MultivaluedMap<String, String>) obj);
        }
    }
    return null;
}
Also used : MessageContentsList(org.apache.cxf.message.MessageContentsList) Form(javax.ws.rs.core.Form) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 72 with MultivaluedMap

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"));
}
Also used : MultivaluedMap(javax.ws.rs.core.MultivaluedMap) WebClient(org.apache.cxf.jaxrs.client.WebClient) Map(java.util.Map) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

Example 73 with MultivaluedMap

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());
}
Also used : MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Matcher(java.util.regex.Matcher) Provider(javax.ws.rs.ext.Provider) Protocol(org.openremote.model.asset.agent.Protocol) DateTimeFormatter(java.time.format.DateTimeFormatter) UriBuilder(javax.ws.rs.core.UriBuilder) IOException(java.io.IOException) Pattern(java.util.regex.Pattern) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) Instant(java.time.Instant) ZoneId(java.time.ZoneId) Matcher(java.util.regex.Matcher) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriBuilder(javax.ws.rs.core.UriBuilder) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 74 with MultivaluedMap

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));
}
Also used : TestingResponse(io.airlift.http.client.testing.TestingResponse) Invocation(javax.ws.rs.client.Invocation) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) List(java.util.List) ProcessingException(javax.ws.rs.ProcessingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProcessingException(javax.ws.rs.ProcessingException) TestingResponse(io.airlift.http.client.testing.TestingResponse) Response(io.airlift.http.client.Response) Map(java.util.Map) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 75 with MultivaluedMap

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();
    }
}
Also used : Path(java.nio.file.Path) HttpCompilationResponse(org.kie.workbench.common.services.backend.compiler.HttpCompilationResponse) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) InputStream(java.io.InputStream) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) HttpCompilationResponse(org.kie.workbench.common.services.backend.compiler.HttpCompilationResponse) Response(javax.ws.rs.core.Response) Git(org.eclipse.jgit.api.Git) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) File(java.io.File) JGitFileSystem(org.uberfire.java.nio.fs.jgit.JGitFileSystem) Test(org.junit.Test)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)135 Map (java.util.Map)67 List (java.util.List)51 HashMap (java.util.HashMap)45 MediaType (javax.ws.rs.core.MediaType)35 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)28 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)27 ArrayList (java.util.ArrayList)24 IOException (java.io.IOException)23 Test (org.junit.Test)21 WebApplicationException (javax.ws.rs.WebApplicationException)19 LinkedHashMap (java.util.LinkedHashMap)18 Type (java.lang.reflect.Type)16 Response (javax.ws.rs.core.Response)16 InputStream (java.io.InputStream)14 OutputStream (java.io.OutputStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)13 Method (java.lang.reflect.Method)11 Optional (java.util.Optional)11