Search in sources :

Example 1 with WebTargetBuilder

use of org.openremote.container.web.WebTargetBuilder in project openremote by openremote.

the class ControllerProtocol method doStart.

@Override
public void doStart(Container container) throws Exception {
    String baseURL = agent.getControllerURI().orElseThrow(() -> new IllegalArgumentException("Missing or invalid controller URI: " + agent));
    URI uri;
    try {
        uri = new URIBuilder(baseURL).build();
    } catch (URISyntaxException e) {
        LOG.log(Level.SEVERE, "Invalid Controller URI", e);
        setConnectionStatus(ConnectionStatus.ERROR);
        throw e;
    }
    client = createClient(executorService, CONNECTION_POOL_SIZE, 70000, null);
    WebTargetBuilder webTargetBuilder = new WebTargetBuilder(client, uri);
    agent.getUsernamePassword().ifPresent(usernamePassword -> {
        LOG.info("Setting BASIC auth credentials for controller");
        webTargetBuilder.setBasicAuthentication(usernamePassword.getUsername(), usernamePassword.getPassword());
    });
    controllerWebTarget = webTargetBuilder.build();
    controller = new Controller(agent.getId());
    controllerHeartbeat = this.executorService.scheduleWithFixedDelay(() -> this.executeHeartbeat(this::onHeartbeatResponse), 0, HEARTBEAT_DELAY_SECONDS, TimeUnit.SECONDS);
}
Also used : WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 2 with WebTargetBuilder

use of org.openremote.container.web.WebTargetBuilder in project openremote by openremote.

the class WebsocketAgentProtocol method doSubscription.

protected void doSubscription(Map<String, List<String>> headers, WebsocketSubscription subscription) {
    if (subscription instanceof WebsocketHTTPSubscription) {
        WebsocketHTTPSubscription httpSubscription = (WebsocketHTTPSubscription) subscription;
        if (TextUtil.isNullOrEmpty(httpSubscription.uri)) {
            LOG.warning("Websocket subscription missing or empty URI so skipping: " + subscription);
            return;
        }
        URI uri;
        try {
            uri = new URI(httpSubscription.uri);
        } catch (URISyntaxException e) {
            LOG.warning("Websocket subscription invalid URI so skipping: " + subscription);
            return;
        }
        if (httpSubscription.method == null) {
            httpSubscription.method = WebsocketHTTPSubscription.Method.valueOf(DEFAULT_HTTP_METHOD);
        }
        if (TextUtil.isNullOrEmpty(httpSubscription.contentType)) {
            httpSubscription.contentType = DEFAULT_CONTENT_TYPE;
        }
        if (httpSubscription.headers != null) {
            headers = headers != null ? new HashMap<>(headers) : new HashMap<>();
            Map<String, List<String>> finalHeaders = headers;
            httpSubscription.headers.forEach((header, values) -> {
                if (values == null || values.isEmpty()) {
                    finalHeaders.remove(header);
                } else {
                    List<String> vals = new ArrayList<>(finalHeaders.compute(header, (h, l) -> l != null ? l : Collections.emptyList()));
                    vals.addAll(values);
                    finalHeaders.put(header, vals);
                }
            });
        }
        WebTargetBuilder webTargetBuilder = new WebTargetBuilder(resteasyClient, uri);
        if (headers != null) {
            webTargetBuilder.setInjectHeaders(headers);
        }
        LOG.fine("Creating web target client for subscription '" + uri + "'");
        ResteasyWebTarget target = webTargetBuilder.build();
        Invocation invocation;
        if (httpSubscription.body == null) {
            invocation = target.request().build(httpSubscription.method.toString());
        } else {
            invocation = target.request().build(httpSubscription.method.toString(), Entity.entity(httpSubscription.body, httpSubscription.contentType));
        }
        Response response = invocation.invoke();
        response.close();
        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
            LOG.warning("WebsocketHttpSubscription returned an un-successful response code: " + response.getStatus());
        }
    } else {
        client.sendMessage(ValueUtil.convert(subscription.body, String.class));
    }
}
Also used : java.util(java.util) DEFAULT_CONTENT_TYPE(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_CONTENT_TYPE) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) URISyntaxException(java.net.URISyntaxException) AttributeRef(org.openremote.model.attribute.AttributeRef) ValueUtil(org.openremote.model.util.ValueUtil) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) Supplier(java.util.function.Supplier) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) Attribute(org.openremote.model.attribute.Attribute) AbstractNettyIOClientProtocol(org.openremote.agent.protocol.io.AbstractNettyIOClientProtocol) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SyslogCategory(org.openremote.model.syslog.SyslogCategory) TextUtil(org.openremote.model.util.TextUtil) URI(java.net.URI) HttpHeaders(org.apache.http.HttpHeaders) OAuthGrant(org.openremote.model.auth.OAuthGrant) ValueType(org.openremote.model.value.ValueType) DEFAULT_HTTP_METHOD(org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_HTTP_METHOD) Pair(org.openremote.model.util.Pair) Invocation(javax.ws.rs.client.Invocation) Logger(java.util.logging.Logger) Entity(javax.ws.rs.client.Entity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Container(org.openremote.model.Container) PROTOCOL(org.openremote.model.syslog.SyslogCategory.PROTOCOL) BasicAuthHelper(org.jboss.resteasy.util.BasicAuthHelper) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Response(javax.ws.rs.core.Response) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ChannelHandler(io.netty.channel.ChannelHandler) WebTargetBuilder.createClient(org.openremote.container.web.WebTargetBuilder.createClient) UsernamePassword(org.openremote.model.auth.UsernamePassword) ProtocolUtil(org.openremote.model.protocol.ProtocolUtil) AttributeExecuteStatus(org.openremote.model.attribute.AttributeExecuteStatus) Invocation(javax.ws.rs.client.Invocation) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Response(javax.ws.rs.core.Response) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)

Example 3 with WebTargetBuilder

use of org.openremote.container.web.WebTargetBuilder in project openremote by openremote.

the class HTTPProtocol method doStart.

@Override
protected void doStart(Container container) throws Exception {
    String baseUri = agent.getBaseURI().orElseThrow(() -> new IllegalArgumentException("Missing or invalid base URI attribute: " + this));
    if (baseUri.endsWith("/")) {
        baseUri = baseUri.substring(0, baseUri.length() - 1);
    }
    URI uri;
    try {
        uri = new URIBuilder(baseUri).build();
    } catch (URISyntaxException e) {
        LOG.log(Level.SEVERE, "Invalid URI", e);
        throw e;
    }
    /* We're going to fail hard and fast if optional meta items are incorrectly configured */
    Optional<OAuthGrant> oAuthGrant = agent.getOAuthGrant();
    Optional<UsernamePassword> usernameAndPassword = agent.getUsernamePassword();
    boolean followRedirects = agent.getFollowRedirects().orElse(false);
    Optional<ValueType.MultivaluedStringMap> headers = agent.getRequestHeaders();
    Optional<ValueType.MultivaluedStringMap> queryParams = agent.getRequestQueryParameters();
    Integer readTimeout = agent.getRequestTimeoutMillis().orElse(null);
    WebTargetBuilder webTargetBuilder;
    if (readTimeout != null) {
        webTargetBuilder = new WebTargetBuilder(WebTargetBuilder.createClient(executorService, WebTargetBuilder.CONNECTION_POOL_SIZE, readTimeout.longValue(), null), uri);
    } else {
        webTargetBuilder = new WebTargetBuilder(client, uri);
    }
    if (oAuthGrant.isPresent()) {
        LOG.info("Adding OAuth");
        webTargetBuilder.setOAuthAuthentication(oAuthGrant.get());
    } else {
        usernameAndPassword.ifPresent(userPass -> {
            LOG.info("Adding Basic Authentication");
            webTargetBuilder.setBasicAuthentication(userPass.getUsername(), userPass.getPassword());
        });
    }
    headers.ifPresent(webTargetBuilder::setInjectHeaders);
    queryParams.ifPresent(webTargetBuilder::setInjectQueryParameters);
    webTargetBuilder.followRedirects(followRedirects);
    LOG.fine("Creating web target client '" + baseUri + "'");
    webTarget = webTargetBuilder.build();
    setConnectionStatus(ConnectionStatus.CONNECTED);
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePassword(org.openremote.model.auth.UsernamePassword) WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) OAuthGrant(org.openremote.model.auth.OAuthGrant)

Example 4 with WebTargetBuilder

use of org.openremote.container.web.WebTargetBuilder in project openremote by openremote.

the class KeycloakIdentityProvider method waitForKeycloak.

protected void waitForKeycloak() {
    boolean keycloakAvailable = false;
    WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, keycloakServiceUri.build());
    ResteasyWebTarget target = targetBuilder.build();
    KeycloakResource keycloakResource = target.proxy(KeycloakResource.class);
    while (!keycloakAvailable) {
        LOG.info("Connecting to Keycloak server: " + keycloakServiceUri.build());
        try {
            pingKeycloak(keycloakResource);
            keycloakAvailable = true;
        } catch (Exception ex) {
            LOG.info("Keycloak server not available, waiting...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
Also used : WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) NotFoundException(javax.ws.rs.NotFoundException)

Example 5 with WebTargetBuilder

use of org.openremote.container.web.WebTargetBuilder in project openremote by openremote.

the class KeycloakIdentityProvider method setActiveCredentials.

/**
 * Update the active credentials used to interact with keycloak; the token endpoint will be overwritten with this
 * instances keycloak server URI and for the master realm.
 */
public synchronized void setActiveCredentials(OAuthGrant grant) {
    if (Objects.equals(this.oAuthGrant, grant)) {
        return;
    }
    this.oAuthGrant = grant;
    // Force token endpoint to master realm as this is the realm we need to be in to do full keycloak CRUD
    if (grant != null) {
        grant.setTokenEndpointUri(getTokenUri("master").toString());
    }
    URI proxyURI = keycloakServiceUri.build();
    WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, proxyURI).setOAuthAuthentication(grant);
    keycloakTarget = targetBuilder.build();
    realmsResourcePool.clear();
    LOG.info("Keycloak proxy URI set to: " + proxyURI);
}
Also used : WebTargetBuilder(org.openremote.container.web.WebTargetBuilder) URI(java.net.URI)

Aggregations

WebTargetBuilder (org.openremote.container.web.WebTargetBuilder)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)3 URIBuilder (org.apache.http.client.utils.URIBuilder)2 ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)2 OAuthGrant (org.openremote.model.auth.OAuthGrant)2 UsernamePassword (org.openremote.model.auth.UsernamePassword)2 ChannelHandler (io.netty.channel.ChannelHandler)1 java.util (java.util)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1 Supplier (java.util.function.Supplier)1 Logger (java.util.logging.Logger)1 NotFoundException (javax.ws.rs.NotFoundException)1 Entity (javax.ws.rs.client.Entity)1 Invocation (javax.ws.rs.client.Invocation)1 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)1 Response (javax.ws.rs.core.Response)1 HttpHeaders (org.apache.http.HttpHeaders)1 ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)1