Search in sources :

Example 41 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 42 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 43 with MultivaluedMap

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);
    }
}
Also used : AlertCriteria(com.thinkbiganalytics.alerts.api.AlertCriteria) AlertManager(com.thinkbiganalytics.alerts.spi.AlertManager) PathParam(javax.ws.rs.PathParam) AlertResponder(com.thinkbiganalytics.alerts.api.AlertResponder) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) AggregatingAlertProvider(com.thinkbiganalytics.alerts.api.core.AggregatingAlertProvider) Path(javax.ws.rs.Path) ApiResponses(io.swagger.annotations.ApiResponses) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) AlertSummary(com.thinkbiganalytics.alerts.api.AlertSummary) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) AlertProvider(com.thinkbiganalytics.alerts.api.AlertProvider) QueryParam(javax.ws.rs.QueryParam) AlertCreateRequest(com.thinkbiganalytics.alerts.rest.model.AlertCreateRequest) RestResponseStatus(com.thinkbiganalytics.rest.model.RestResponseStatus) Consumes(javax.ws.rs.Consumes) Alert(com.thinkbiganalytics.alerts.api.Alert) AlertUpdateRequest(com.thinkbiganalytics.alerts.rest.model.AlertUpdateRequest) DefaultValue(javax.ws.rs.DefaultValue) AccessController(com.thinkbiganalytics.security.AccessController) AlertRange(com.thinkbiganalytics.alerts.rest.model.AlertRange) Formatters(com.thinkbiganalytics.Formatters) URI(java.net.URI) Named(javax.inject.Named) Api(io.swagger.annotations.Api) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) OperationsAccessControl(com.thinkbiganalytics.jobrepo.security.OperationsAccessControl) Collection(java.util.Collection) AlertType(com.thinkbiganalytics.alerts.rest.model.AlertType) Set(java.util.Set) Collectors(java.util.stream.Collectors) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) Component(org.springframework.stereotype.Component) ApiResponse(io.swagger.annotations.ApiResponse) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) KyloEntityAwareAlertManager(com.thinkbiganalytics.metadata.alerts.KyloEntityAwareAlertManager) UriInfo(javax.ws.rs.core.UriInfo) AlertsModel(com.thinkbiganalytics.alerts.rest.AlertsModel) AlertSummaryGrouped(com.thinkbiganalytics.alerts.rest.model.AlertSummaryGrouped) AlertCriteria(com.thinkbiganalytics.alerts.api.AlertCriteria) AlertCriteriaInput(com.thinkbiganalytics.alerts.api.core.AlertCriteriaInput) AlertResponse(com.thinkbiganalytics.alerts.api.AlertResponse) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 44 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 45 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