Search in sources :

Example 1 with ResteasyWebTarget

use of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget in project openremote by openremote.

the class HttpClientProtocol method doLinkAttribute.

@Override
protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
    AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();
    Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;
    clientAndFailureCodes = clientMap.get(protocolConfigurationRef);
    WebTarget client = clientAndFailureCodes != null ? clientAndFailureCodes.key : null;
    if (client == null) {
        LOG.warning("Attempt to link attribute to non existent protocol configuration: " + attribute.getReferenceOrThrow());
        return;
    }
    String method = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_METHOD, StringValue.class, false, true).map(StringValue::getString).orElse(DEFAULT_HTTP_METHOD);
    String path = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_PATH, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    String contentType = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_CONTENT_TYPE, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    Value body = attribute.getMetaItem(META_ATTRIBUTE_BODY).flatMap(AbstractValueHolder::getValue).orElse(null);
    List<Integer> failureCodes = attribute.getMetaItem(META_FAILURE_CODES).flatMap(AbstractValueHolder::getValueAsArray).flatMap(arrayValue -> Values.getArrayElements(arrayValue, NumberValue.class, true, false, number -> Values.getIntegerCoerced(number).orElse(null))).map(fCodes -> {
        if (clientAndFailureCodes.value != null) {
            fCodes.addAll(clientAndFailureCodes.value);
        }
        return fCodes;
    }).orElseGet(() -> {
        if (clientAndFailureCodes.value != null) {
            return clientAndFailureCodes.value;
        }
        return null;
    });
    MultivaluedMap<String, String> headers = Values.getMetaItemValueOrThrow(attribute, META_HEADERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, true)).orElse(null);
    MultivaluedMap<String, String> queryParams = Values.getMetaItemValueOrThrow(attribute, META_QUERY_PARAMETERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, false)).orElse(null);
    Optional<Integer> pollingSeconds = Values.getMetaItemValueOrThrow(attribute, META_ATTRIBUTE_POLLING_SECONDS, NumberValue.class, false, true).map(polling -> Values.getIntegerCoerced(polling).map(seconds -> seconds < 1 ? null : seconds).orElseThrow(() -> new IllegalArgumentException("Polling seconds meta item must be an integer >= 1")));
    final AttributeRef attributeRef = attribute.getReferenceOrThrow();
    boolean updateConnectionStatus = !pollingMap.containsKey(protocolConfigurationRef);
    HttpClientRequest clientRequest = buildClientRequest(client, path, method, headers, queryParams, failureCodes, updateConnectionStatus, body, contentType);
    LOG.fine("Creating HTTP request for linked attribute '" + clientRequest + "': " + attributeRef);
    requestMap.put(attributeRef, clientRequest);
    pollingSeconds.ifPresent(seconds -> pollingMap.put(attributeRef, schedulePollingRequest(attributeRef, protocolConfigurationRef, clientRequest, seconds)));
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) ProtocolConfiguration(org.openremote.model.asset.agent.ProtocolConfiguration) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) HashMap(java.util.HashMap) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) HttpMethod(javax.ws.rs.HttpMethod) Level(java.util.logging.Level) Container(org.openremote.container.Container) MediaType(javax.ws.rs.core.MediaType) Future(java.util.concurrent.Future) Map(java.util.Map) TextUtil(org.openremote.model.util.TextUtil) PROTOCOL_NAMESPACE(org.openremote.model.Constants.PROTOCOL_NAMESPACE) AbstractValueHolder(org.openremote.model.AbstractValueHolder) Pair(org.openremote.model.util.Pair) IOException(java.io.IOException) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) AssetMeta(org.openremote.model.asset.AssetMeta) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) org.openremote.model.value(org.openremote.model.value) Response(javax.ws.rs.core.Response) org.openremote.model.attribute(org.openremote.model.attribute) Optional(java.util.Optional) WebTarget(javax.ws.rs.client.WebTarget) AssetAttribute(org.openremote.model.asset.AssetAttribute) Protocol(org.openremote.agent.protocol.Protocol) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) List(java.util.List) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) WebTarget(javax.ws.rs.client.WebTarget)

Example 2 with ResteasyWebTarget

use of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget in project openremote by openremote.

the class HttpClientProtocol method doLinkProtocolConfiguration.

@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
    final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
    if (!protocolConfiguration.isEnabled()) {
        updateStatus(protocolRef, ConnectionStatus.DISABLED);
        return;
    }
    String baseUri = protocolConfiguration.getMetaItem(META_PROTOCOL_BASE_URI).flatMap(AbstractValueHolder::getValueAsString).orElseThrow(() -> new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_BASE_URI));
    /* We're going to fail hard and fast if optional meta items are incorrectly configured */
    Optional<OAuthGrant> oAuthGrant = getOAuthGrant(protocolConfiguration);
    Optional<StringValue> username = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_USERNAME, StringValue.class, false, true);
    Optional<StringValue> password = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PASSWORD, StringValue.class, false, true);
    boolean followRedirects = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_FOLLOW_REDIRECTS, BooleanValue.class, false, true).map(BooleanValue::getBoolean).orElse(false);
    List<Integer> failureCodes = protocolConfiguration.getMetaItem(META_FAILURE_CODES).flatMap(AbstractValueHolder::getValueAsArray).flatMap(arrayValue -> Values.getArrayElements(arrayValue, NumberValue.class, true, false, number -> Values.getIntegerCoerced(number).orElse(null))).orElse(null);
    Optional<MultivaluedMap<String, String>> headers = Values.getMetaItemValueOrThrow(protocolConfiguration, META_HEADERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, true));
    Optional<MultivaluedMap<String, String>> queryParams = Values.getMetaItemValueOrThrow(protocolConfiguration, META_QUERY_PARAMETERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, false));
    String pingPath = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PING_PATH, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    if ((username.isPresent() && !password.isPresent()) || (!username.isPresent() && password.isPresent())) {
        throw new IllegalArgumentException("Both username and password must be set for basic authentication");
    }
    WebTargetBuilder webTargetBuilder = new WebTargetBuilder(baseUri);
    if (oAuthGrant.isPresent()) {
        LOG.info("Adding OAuth");
        webTargetBuilder.setOAuthAuthentication(oAuthGrant.get());
    } else {
        // noinspection ConstantConditions
        username.ifPresent(stringValue -> {
            LOG.info("Adding Basic Authentication");
            webTargetBuilder.setBasicAuthentication(stringValue.getString(), password.get().getString());
        });
    }
    headers.ifPresent(webTargetBuilder::setInjectHeaders);
    queryParams.ifPresent(webTargetBuilder::setInjectQueryParameters);
    webTargetBuilder.followRedirects(followRedirects);
    LOG.fine("Creating web target client '" + baseUri + "'");
    ResteasyWebTarget client = webTargetBuilder.build();
    clientMap.put(protocolRef, new Pair<>(client, failureCodes));
    updateStatus(protocolRef, ConnectionStatus.UNKNOWN);
    if (pingPath == null) {
        return;
    }
    String pingMethod = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PING_METHOD, StringValue.class, false, true).map(StringValue::getString).orElse(DEFAULT_HTTP_METHOD);
    Value pingBody = protocolConfiguration.getMetaItem(META_PROTOCOL_PING_BODY).flatMap(AbstractValueHolder::getValue).orElse(null);
    MultivaluedMap<String, String> pingQueryParams = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PING_QUERY_PARAMETERS, ObjectValue.class, false, true).flatMap(objectValue -> getMultivaluedMap(objectValue, false)).orElse(null);
    Integer pingPollingSeconds = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PING_SECONDS, NumberValue.class, false, true).map(polling -> Values.getIntegerCoerced(polling).map(seconds -> seconds < 1 ? null : seconds).orElseThrow(() -> new IllegalArgumentException("Ping polling seconds meta item must be an integer >= 1"))).orElse(DEFAULT_PING_SECONDS);
    String contentType = Values.getMetaItemValueOrThrow(protocolConfiguration, META_PROTOCOL_PING_CONTENT_TYPE, StringValue.class, false, true).map(StringValue::getString).orElse(null);
    HttpClientRequest pingRequest = buildClientRequest(client, pingPath, pingMethod, null, pingQueryParams, null, true, pingBody, contentType);
    LOG.info("Creating ping polling request '" + pingRequest + "'");
    requestMap.put(protocolRef, pingRequest);
    pollingMap.put(protocolRef, schedulePollingRequest(null, protocolRef, pingRequest, pingPollingSeconds));
}
Also used : ScheduledFuture(java.util.concurrent.ScheduledFuture) ProtocolConfiguration(org.openremote.model.asset.agent.ProtocolConfiguration) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) HashMap(java.util.HashMap) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) HttpMethod(javax.ws.rs.HttpMethod) Level(java.util.logging.Level) Container(org.openremote.container.Container) MediaType(javax.ws.rs.core.MediaType) Future(java.util.concurrent.Future) Map(java.util.Map) TextUtil(org.openremote.model.util.TextUtil) PROTOCOL_NAMESPACE(org.openremote.model.Constants.PROTOCOL_NAMESPACE) AbstractValueHolder(org.openremote.model.AbstractValueHolder) Pair(org.openremote.model.util.Pair) IOException(java.io.IOException) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) AbstractProtocol(org.openremote.agent.protocol.AbstractProtocol) AssetMeta(org.openremote.model.asset.AssetMeta) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) org.openremote.model.value(org.openremote.model.value) Response(javax.ws.rs.core.Response) org.openremote.model.attribute(org.openremote.model.attribute) Optional(java.util.Optional) WebTarget(javax.ws.rs.client.WebTarget) AssetAttribute(org.openremote.model.asset.AssetAttribute) Protocol(org.openremote.agent.protocol.Protocol) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) AbstractValueHolder(org.openremote.model.AbstractValueHolder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 3 with ResteasyWebTarget

use of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget in project openremote by openremote.

the class WebTargetBuilder method build.

public ResteasyWebTarget build() {
    ResteasyWebTarget target = client.target(uri);
    if (!failureResponses.isEmpty()) {
        // Put a filter with max priority in the filter chain
        target.register(new PermanentFailureFilter(failureResponses), 1);
    }
    if (oAuthGrant != null) {
        WebTarget authTarget = client.target(oAuthGrant.tokenEndpointUri);
        OAuthFilter oAuthFilter = new OAuthFilter(authTarget, oAuthGrant);
        target.register(oAuthFilter, Priorities.AUTHENTICATION);
    } else if (basicAuthentication != null) {
        target.register(basicAuthentication, Priorities.AUTHENTICATION);
    }
    if (injectHeaders != null) {
        target.register(new HeaderInjectorFilter(injectHeaders));
    }
    if (injectQueryParameters != null) {
        target.register(new QueryParameterInjectorFilter(injectQueryParameters, null));
    }
    if (followRedirects) {
        target.register(new FollowRedirectFilter());
    }
    return target;
}
Also used : ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) WebTarget(javax.ws.rs.client.WebTarget)

Example 4 with ResteasyWebTarget

use of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget in project kie-wb-common by kiegroup.

the class RuntimeEndpointsTestIT method checkDockerService.

@Ignore
public void checkDockerService() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(APP_URL);
    ResteasyWebTarget restEasyTarget = (ResteasyWebTarget) target;
    RuntimeProvisioningService proxy = restEasyTarget.proxy(RuntimeProvisioningService.class);
    ProviderTypeList allProviderTypes = proxy.getProviderTypes(0, 10, "", true);
    assertNotNull(allProviderTypes);
    assertEquals(3, allProviderTypes.getItems().size());
    DockerProviderConfig dockerProviderConfig = new DockerProviderConfigImpl();
    proxy.registerProvider(dockerProviderConfig);
    ProviderList allProviders = proxy.getProviders(0, 10, "", true);
    assertEquals(1, allProviders.getItems().size());
    assertTrue(allProviders.getItems().get(0) instanceof DockerProvider);
    DockerProvider dockerProvider = (DockerProvider) allProviders.getItems().get(0);
    DockerRuntimeConfig runtimeConfig = new DockerRuntimeConfigImpl(dockerProvider, "kitematic/hello-world-nginx", "8080", true);
    RuntimeList allRuntimes = proxy.getRuntimes(0, 10, "", true);
    assertEquals(0, allRuntimes.getItems().size());
    String newRuntime = proxy.newRuntime(runtimeConfig);
    allRuntimes = proxy.getRuntimes(0, 10, "", true);
    assertEquals(1, allRuntimes.getItems().size());
    Runtime runtime = allRuntimes.getItems().get(0);
    assertTrue(runtime instanceof DockerRuntime);
    DockerRuntime dockerRuntime = (DockerRuntime) runtime;
    assertEquals("Running", dockerRuntime.getState().getState());
    proxy.stopRuntime(newRuntime);
    allRuntimes = proxy.getRuntimes(0, 10, "", true);
    assertEquals(1, allRuntimes.getItems().size());
    runtime = allRuntimes.getItems().get(0);
    assertTrue(runtime instanceof DockerRuntime);
    dockerRuntime = (DockerRuntime) runtime;
    assertEquals("Stopped", dockerRuntime.getState().getState());
    proxy.destroyRuntime(newRuntime, true);
    allRuntimes = proxy.getRuntimes(0, 10, "", true);
    assertEquals(0, allRuntimes.getItems().size());
}
Also used : ProviderList(org.guvnor.ala.services.api.itemlist.ProviderList) DockerProvider(org.guvnor.ala.docker.model.DockerProvider) DockerProviderConfigImpl(org.guvnor.ala.docker.config.impl.DockerProviderConfigImpl) DockerRuntimeConfigImpl(org.guvnor.ala.docker.config.impl.DockerRuntimeConfigImpl) DockerProviderConfig(org.guvnor.ala.docker.config.DockerProviderConfig) ProviderTypeList(org.guvnor.ala.services.api.itemlist.ProviderTypeList) DockerRuntime(org.guvnor.ala.docker.model.DockerRuntime) OpenShiftRuntime(org.guvnor.ala.openshift.model.OpenShiftRuntime) DockerRuntime(org.guvnor.ala.docker.model.DockerRuntime) Runtime(org.guvnor.ala.runtime.Runtime) RuntimeList(org.guvnor.ala.services.api.itemlist.RuntimeList) RuntimeProvisioningService(org.guvnor.ala.services.api.RuntimeProvisioningService) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) DockerRuntimeConfig(org.guvnor.ala.docker.config.DockerRuntimeConfig) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Ignore(org.junit.Ignore)

Example 5 with ResteasyWebTarget

use of org.jboss.resteasy.client.jaxrs.ResteasyWebTarget in project tutorials by eugenp.

the class RestEasyClientLiveTest method testAddMovieMultiConnection.

@Test
public void testAddMovieMultiConnection() {
    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);
    final Response batmanResponse = proxy.addMovie(batmanMovie);
    final Response transformerResponse = proxy.addMovie(transformerMovie);
    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }
    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }
    batmanResponse.close();
    transformerResponse.close();
    cm.close();
}
Also used : Response(javax.ws.rs.core.Response) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ApacheHttpClient4Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) ServicesInterface(com.baeldung.client.ServicesInterface) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) Test(org.junit.Test)

Aggregations

ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)57 ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)41 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)18 Response (javax.ws.rs.core.Response)13 NotConnectedRestException (org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException)10 Test (org.junit.Test)9 WebTarget (javax.ws.rs.client.WebTarget)8 ServicesInterface (com.baeldung.client.ServicesInterface)6 IOException (java.io.IOException)6 Client (javax.ws.rs.client.Client)5 ApacheHttpClient4Engine (org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine)5 TimeUnit (java.util.concurrent.TimeUnit)4 Invocation (javax.ws.rs.client.Invocation)4 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)4 NotConnectedException (org.ow2.proactive.scheduler.common.exception.NotConnectedException)4 HashMap (java.util.HashMap)3 List (java.util.List)3 Locale (java.util.Locale)3 Map (java.util.Map)3 Consumer (java.util.function.Consumer)3