Search in sources :

Example 1 with KuraConnectException

use of org.eclipse.kura.KuraConnectException in project kura by eclipse.

the class HttpDownloadCountingOutputStream method startWork.

@Override
public void startWork() throws KuraException {
    this.executor = Executors.newSingleThreadExecutor();
    this.future = this.executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            URL localUrl = null;
            boolean shouldAuthenticate = false;
            try {
                shouldAuthenticate = HttpDownloadCountingOutputStream.this.options.getUsername() != null && HttpDownloadCountingOutputStream.this.options.getPassword() != null && !(HttpDownloadCountingOutputStream.this.options.getUsername().trim().isEmpty() && !HttpDownloadCountingOutputStream.this.options.getPassword().trim().isEmpty());
                if (shouldAuthenticate) {
                    Authenticator.setDefault(new Authenticator() {

                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(HttpDownloadCountingOutputStream.this.options.getUsername(), HttpDownloadCountingOutputStream.this.options.getPassword().toCharArray());
                        }
                    });
                }
                localUrl = new URL(HttpDownloadCountingOutputStream.this.m_downloadURL);
                URLConnection urlConnection = localUrl.openConnection();
                int connectTimeout = getConnectTimeout();
                int readTimeout = getPropReadTimeout();
                urlConnection.setConnectTimeout(connectTimeout);
                urlConnection.setReadTimeout(readTimeout);
                testConnectionProtocol(urlConnection);
                HttpDownloadCountingOutputStream.this.is = localUrl.openStream();
                String s = urlConnection.getHeaderField("Content-Length");
                s_logger.info("Content-lenght: " + s);
                setTotalBytes(s != null ? Integer.parseInt(s) : -1);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), 0, HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null);
                int bufferSize = getBufferSize();
                if (bufferSize == 0 && getTotalBytes() > 0) {
                    int newSize = Math.round(HttpDownloadCountingOutputStream.this.totalBytes / 100 * 1);
                    bufferSize = newSize;
                    setBufferSize(newSize);
                } else if (bufferSize == 0) {
                    int newSize = 1024 * 4;
                    bufferSize = newSize;
                    setBufferSize(newSize);
                }
                long numBytes = IOUtils.copyLarge(HttpDownloadCountingOutputStream.this.is, HttpDownloadCountingOutputStream.this, new byte[bufferSize]);
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), numBytes, HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.COMPLETED, null);
            } catch (IOException e) {
                postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), getByteCount(), HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.FAILED, e.getMessage());
                throw new KuraConnectException(e);
            } finally {
                if (HttpDownloadCountingOutputStream.this.is != null) {
                    try {
                        HttpDownloadCountingOutputStream.this.is.close();
                    } catch (IOException e) {
                    }
                }
                try {
                    close();
                } catch (IOException e) {
                }
                localUrl = null;
                if (shouldAuthenticate) {
                    Authenticator.setDefault(null);
                }
            }
            return null;
        }
    });
    try {
        this.future.get();
    } catch (ExecutionException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    } catch (InterruptedException ex) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex);
    }
}
Also used : KuraConnectException(org.eclipse.kura.KuraConnectException) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URLConnection(java.net.URLConnection) KuraException(org.eclipse.kura.KuraException) ExecutionException(java.util.concurrent.ExecutionException) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 2 with KuraConnectException

use of org.eclipse.kura.KuraConnectException in project kura by eclipse.

the class GwtStatusServiceImpl method connectDataService.

@Override
public void connectDataService(GwtXSRFToken xsrfToken) throws GwtKuraException {
    checkXSRFToken(xsrfToken);
    DataService dataService = ServiceLocator.getInstance().getService(DataService.class);
    int counter = 10;
    try {
        dataService.connect();
        while (!dataService.isConnected() && counter > 0) {
            Thread.sleep(1000);
            counter--;
        }
    } catch (KuraConnectException e) {
        s_logger.warn("Error connecting", e);
        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Error connecting");
    } catch (InterruptedException e) {
        s_logger.warn("Interrupt Exception", e);
        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Interrupt Exception");
    } catch (IllegalStateException e) {
        s_logger.warn("Illegal client state", e);
        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Illegal client state");
    }
}
Also used : GwtKuraException(org.eclipse.kura.web.shared.GwtKuraException) KuraConnectException(org.eclipse.kura.KuraConnectException) DataService(org.eclipse.kura.data.DataService)

Example 3 with KuraConnectException

use of org.eclipse.kura.KuraConnectException in project kura by eclipse.

the class GwtStatusServiceImpl method connectDataService.

@Override
public void connectDataService(GwtXSRFToken xsrfToken, String connectionId) throws GwtKuraException {
    checkXSRFToken(xsrfToken);
    Collection<ServiceReference<CloudService>> cloudServiceReferences = ServiceLocator.getInstance().getServiceReferences(CloudService.class, null);
    for (ServiceReference<CloudService> cloudServiceReference : cloudServiceReferences) {
        String cloudServicePid = (String) cloudServiceReference.getProperty(KURA_SERVICE_PID);
        if (cloudServicePid.endsWith(connectionId)) {
            String dataServiceRef = (String) cloudServiceReference.getProperty(DATA_SERVICE_REFERENCE_NAME + ComponentConstants.REFERENCE_TARGET_SUFFIX);
            Collection<ServiceReference<DataService>> dataServiceReferences = ServiceLocator.getInstance().getServiceReferences(DataService.class, dataServiceRef);
            for (ServiceReference<DataService> dataServiceReference : dataServiceReferences) {
                DataService dataService = ServiceLocator.getInstance().getService(dataServiceReference);
                if (dataService != null) {
                    int counter = 10;
                    try {
                        dataService.connect();
                        while (!dataService.isConnected() && counter > 0) {
                            Thread.sleep(1000);
                            counter--;
                        }
                    } catch (KuraConnectException e) {
                        s_logger.warn("Error connecting", e);
                        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Error connecting");
                    } catch (InterruptedException e) {
                        s_logger.warn("Interrupt Exception", e);
                        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Interrupt Exception");
                    } catch (IllegalStateException e) {
                        s_logger.warn("Illegal client state", e);
                        throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR, e, "Illegal client state");
                    }
                }
                ServiceLocator.getInstance().ungetService(dataServiceReference);
            }
        }
        ServiceLocator.getInstance().ungetService(cloudServiceReference);
    }
}
Also used : GwtKuraException(org.eclipse.kura.web.shared.GwtKuraException) KuraConnectException(org.eclipse.kura.KuraConnectException) CloudService(org.eclipse.kura.cloud.CloudService) ServiceReference(org.osgi.framework.ServiceReference) DataService(org.eclipse.kura.data.DataService)

Example 4 with KuraConnectException

use of org.eclipse.kura.KuraConnectException in project kura by eclipse.

the class MqttDataTransport method connect.

// ----------------------------------------------------------------
// 
// Service APIs
// 
// ----------------------------------------------------------------
@Override
public synchronized void connect() throws KuraConnectException {
    // We treat this as an application bug.
    if (isConnected()) {
        s_logger.error("Already connected");
        throw new IllegalStateException("Already connected");
    // TODO: define an KuraRuntimeException
    }
    // Attempt to setup the MQTT session
    setupMqttSession();
    if (this.m_mqttClient == null) {
        s_logger.error("Invalid configuration");
        throw new IllegalStateException("Invalid configuration");
    // TODO: define an KuraRuntimeException
    }
    s_logger.info("# ------------------------------------------------------------");
    s_logger.info("#  Connection Properties");
    s_logger.info("#  broker    = " + this.m_clientConf.getBrokerUrl());
    s_logger.info("#  clientId  = " + this.m_clientConf.getClientId());
    s_logger.info("#  username  = " + this.m_clientConf.getConnectOptions().getUserName());
    s_logger.info("#  password  = XXXXXXXXXXXXXX");
    s_logger.info("#  keepAlive = " + this.m_clientConf.getConnectOptions().getKeepAliveInterval());
    s_logger.info("#  timeout   = " + this.m_clientConf.getConnectOptions().getConnectionTimeout());
    s_logger.info("#  cleanSession    = " + this.m_clientConf.getConnectOptions().isCleanSession());
    s_logger.info("#  MQTT version    = " + getMqttVersionLabel(this.m_clientConf.getConnectOptions().getMqttVersion()));
    s_logger.info("#  willDestination = " + this.m_clientConf.getConnectOptions().getWillDestination());
    s_logger.info("#  willMessage     = " + this.m_clientConf.getConnectOptions().getWillMessage());
    s_logger.info("#");
    s_logger.info("#  Connecting...");
    // Register the component in the CloudConnectionStatus service
    this.m_cloudConnectionStatusService.register(this);
    // Update status notification service
    this.m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.FAST_BLINKING);
    // connect
    try {
        IMqttToken connectToken = this.m_mqttClient.connect(this.m_clientConf.getConnectOptions());
        connectToken.waitForCompletion(getTimeToWaitMillis() * 3);
        s_logger.info("#  Connected!");
        s_logger.info("# ------------------------------------------------------------");
        // Update status notification service
        this.m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.ON);
    } catch (MqttException e) {
        s_logger.warn("xxxxx  Connect failed. Forcing disconnect. xxxxx {}", e);
        try {
            // prevent callbacks from a zombie client
            this.m_mqttClient.setCallback(null);
            this.m_mqttClient.close();
        } catch (Exception de) {
            s_logger.warn("Forced disconnect exception.", de);
        } finally {
            this.m_mqttClient = null;
        }
        // Update status notification service
        this.m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.OFF);
        throw new KuraConnectException(e, "Cannot connect");
    } finally {
        // Always unregister from CloudConnectionStatus service so to switch to the previous state
        this.m_cloudConnectionStatusService.unregister(this);
    }
    // notify the listeners
    this.m_dataTransportListeners.onConnectionEstablished(this.m_newSession);
}
Also used : MqttException(org.eclipse.paho.client.mqttv3.MqttException) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) KuraConnectException(org.eclipse.kura.KuraConnectException) KuraNotConnectedException(org.eclipse.kura.KuraNotConnectedException) KuraTimeoutException(org.eclipse.kura.KuraTimeoutException) KuraException(org.eclipse.kura.KuraException) KuraTooManyInflightMessagesException(org.eclipse.kura.KuraTooManyInflightMessagesException) KuraConnectException(org.eclipse.kura.KuraConnectException) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttPersistenceException(org.eclipse.paho.client.mqttv3.MqttPersistenceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

KuraConnectException (org.eclipse.kura.KuraConnectException)4 KuraException (org.eclipse.kura.KuraException)2 DataService (org.eclipse.kura.data.DataService)2 GwtKuraException (org.eclipse.kura.web.shared.GwtKuraException)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Authenticator (java.net.Authenticator)1 HttpURLConnection (java.net.HttpURLConnection)1 PasswordAuthentication (java.net.PasswordAuthentication)1 URL (java.net.URL)1 URLConnection (java.net.URLConnection)1 Callable (java.util.concurrent.Callable)1 ExecutionException (java.util.concurrent.ExecutionException)1 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)1 KuraNotConnectedException (org.eclipse.kura.KuraNotConnectedException)1 KuraTimeoutException (org.eclipse.kura.KuraTimeoutException)1 KuraTooManyInflightMessagesException (org.eclipse.kura.KuraTooManyInflightMessagesException)1 CloudService (org.eclipse.kura.cloud.CloudService)1 IMqttToken (org.eclipse.paho.client.mqttv3.IMqttToken)1 MqttException (org.eclipse.paho.client.mqttv3.MqttException)1