當前位置: 首頁>>代碼示例>>Java>>正文


Java MqttException類代碼示例

本文整理匯總了Java中org.eclipse.paho.client.mqttv3.MqttException的典型用法代碼示例。如果您正苦於以下問題:Java MqttException類的具體用法?Java MqttException怎麽用?Java MqttException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MqttException類屬於org.eclipse.paho.client.mqttv3包,在下文中一共展示了MqttException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: connect

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
public void connect() {
    try {
        client = new MqttAsyncClient((configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(),
                getClientId(), new MemoryPersistence());
        client.setCallback(this);
        clientOptions = new MqttConnectOptions();
        clientOptions.setCleanSession(true);
        if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) {
            Properties sslProperties = new Properties();
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
            sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false);
            clientOptions.setSSLProperties(sslProperties);
        }
        configuration.getCredentials().configure(clientOptions);
        checkConnection();
        if (configuration.getAttributeUpdates() != null) {
            configuration.getAttributeUpdates().forEach(mapping ->
                    gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
        if (configuration.getServerSideRpc() != null) {
            configuration.getServerSideRpc().forEach(mapping ->
                    gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
    } catch (MqttException e) {
        log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
        throw new RuntimeException("MQTT broker connection failed!", e);
    }
}
 
開發者ID:osswangxining,項目名稱:iot-edge-greengrass,代碼行數:33,代碼來源:MqttBrokerMonitor.java

示例2: testWithDefaultStatusPublisher

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
@Test
public void testWithDefaultStatusPublisher() throws MqttException, InterruptedException
{
    StaticApplicationContext applicationContext = getStaticApplicationContext();
    PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
        BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(),
        MqttClientConnectionType.PUBSUB, null);
    service.setApplicationEventPublisher(applicationContext);
    service.start();
    Assert.assertTrue(service.isConnected());
    Assert.assertTrue(service.isStarted());
    Thread.sleep(1100);
    Assert.assertEquals(0, messageDeliveredCount.get());
    Assert.assertEquals(0, messagePublishedCount.get());
    service.stop();
    service.close();
}
 
開發者ID:christophersmith,項目名稱:summer-mqtt,代碼行數:18,代碼來源:ConnectionStatusTest.java

示例3: stopListening

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
@Override
public void stopListening() {
    try {
        if (orderExecutorService != null) {
            ProcessorHelper.shutdownProcessors(orderExecutorService, orderQueue, 5, TimeUnit.SECONDS);
        }
        if (mqttClient.isConnected()) {
            LOGGER.info("Stopping MQTT client.");
            String[] paths = comboBySource.keySet().toArray(new String[comboBySource.size()]);
            mqttClient.unsubscribe(paths);
            mqttClient.disconnect();
        } else {
            LOGGER.info("MQTT client already stopped.");
        }
    } catch (MqttException ex) {
        LOGGER.error("Problem while disconnecting!", ex);
    }
}
 
開發者ID:hylkevds,項目名稱:SensorThingsProcessor,代碼行數:19,代碼來源:ProcessorBatchAggregate.java

示例4: initializeMqttClient

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(),
        cloudIotOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotOptions.UNUSED_ACCOUNT_NAME);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId()));

    mqttClient.connect(options);
    mReady.set(true);
}
 
開發者ID:androidthings,項目名稱:sensorhub-cloud-iot,代碼行數:20,代碼來源:MQTTPublisher.java

示例5: unRealizeSubscriptions

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void unRealizeSubscriptions ( final Hive hive, final ObjectPool<MqttItemToTopic> pool ) throws InvalidSessionException, MqttException
{
    if ( this.poolListener != null )
    {
        pool.removeListener ( this.poolListener );
    }
    if ( this.session != null )
    {
        this.session.setListener ( (ItemChangeListener)null );
        hive.closeSession ( this.session );
    }
    if ( this.client != null )
    {
        this.client.setCallback ( null );
    }
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:17,代碼來源:MqttExporter.java

示例6: unsubscribe

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void unsubscribe ( final Session session, final MqttItemToTopic itemToTopic ) throws InvalidSessionException, InvalidItemException, MqttException
{
    this.executor.submit ( new Callable<Void> () {
        @Override
        public Void call () throws Exception
        {
            logger.trace ( "unsubscribe () called with '{}'", itemToTopic );
            if ( itemToTopic.isReadable () )
            {
                MqttExporter.this.itemsToReadTopics.remove ( itemToTopic.getItemId () );
                MqttExporter.this.hive.unsubscribeItem ( session, itemToTopic.getItemId () );
            }
            if ( itemToTopic.isWritable () )
            {
                logger.trace ( "unsubscribe () called on topic '{}'", makeWriteTopicName ( itemToTopic ) );
                MqttExporter.this.itemsToWriteTopics.remove ( itemToTopic.getItemId () );
                MqttExporter.this.client.unsubscribe ( makeWriteTopicName ( itemToTopic ) );
            }
            return null;
        }
    } );
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:23,代碼來源:MqttExporter.java

示例7: writeMessageToItem

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
/**
 * convert received mqtt message and write it to item
 *
 * @param hive
 * @param session
 * @param itemId
 * @param message
 * @throws InvalidSessionException
 * @throws PermissionDeniedException
 * @throws InvalidItemException
 * @throws MqttException
 */
private void writeMessageToItem ( final Hive hive, final Session session, final String itemId, final MqttMessage message ) throws InvalidSessionException, PermissionDeniedException, InvalidItemException, MqttException
{
    final DataItemValue div = messageToValue ( itemId, message );
    if ( div != null )
    {
        if ( div.getValue () != null )
        {
            hive.startWrite ( session, itemId, div.getValue (), null, null );
        }
        if ( div.getAttributes () != null && !div.getAttributes ().isEmpty () )
        {
            hive.startWriteAttributes ( session, itemId, div.getAttributes (), null, null );
        }
    }
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:28,代碼來源:MqttExporter.java

示例8: messageToValue

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
/**
 * @param itemId
 * @param message
 *            from MQTT topic
 * @return converted value
 * @throws MqttException
 */
private DataItemValue messageToValue ( final String itemId, final MqttMessage message ) throws MqttException
{
    final DataItemValue div;
    try
    {
        div = gson.fromJson ( new String ( message.getPayload (), "UTF-8" ), DataItemValue.class );
        if ( message.isRetained () || message.isDuplicate () )
        {
            logger.info ( "message is retained/duplicate, will not write" );
            return null;
        }
        return div;
    }
    catch ( JsonSyntaxException | UnsupportedEncodingException e1 )
    {
        logger.warn ( "could not parse message {}", message );
        return null;
    }
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:27,代碼來源:MqttExporter.java

示例9: MqttClientKetiSub

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
public MqttClientKetiSub(String serverUrl) {
	
	this.mqttServerUrl = serverUrl;
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
開發者ID:IoTKETI,項目名稱:nCube-Thyme-Java,代碼行數:20,代碼來源:MqttClientKetiSub.java

示例10: MqttClientKetiPub

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
public MqttClientKetiPub(String serverUrl) {
	
	this.mqttServerUrl = serverUrl;
	
	System.out.println("[KETI MQTT Client] Client Initialize");
	
	try {
		mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);
		
		while(!mqc.isConnected()){
			mqc.connect();
			System.out.println("[KETI MQTT Client] Connection try");
		}
		
		System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
開發者ID:IoTKETI,項目名稱:nCube-Thyme-Java,代碼行數:20,代碼來源:MqttClientKetiPub.java

示例11: onPublish

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void onPublish(final String requestId, final String topic, final byte[] payload) {
    if (!clientIsConnected()) {
        broadcastException(BROADCAST_EXCEPTION, requestId,
                           new Exception("Can't publish to topic: " + topic + ", client not connected!"));
        return;
    }

    try {
        MQTTServiceLogger.debug("onPublish", "Publishing to topic: " + topic + ", payload with size " + payload.length);
        MqttMessage message = new MqttMessage(payload);
        message.setQos(0);
        mClient.publish(topic, message);
        MQTTServiceLogger.debug("onPublish", "Successfully published to topic: " + topic + ", payload: " + payload);

        broadcast(BROADCAST_PUBLISH_SUCCESS, requestId,
                PARAM_TOPIC, topic
        );

    } catch (Exception exc) {
        broadcastException(BROADCAST_EXCEPTION, requestId, new MqttException(exc));
    }
}
 
開發者ID:iGenius-Srl,項目名稱:android-mqtt-service,代碼行數:23,代碼來源:MQTTService.java

示例12: connectClient

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void connectClient() {
  try {
    client = new MqttClient(broker, clientId);
    client.setCallback(this);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(user);
    connOpts.setPassword(password.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(OUTGOING_MQTT_KEEP_ALIVE);
    logger.debug("Connecting to broker:  " + broker);
    client.connect(connOpts);
    logger.debug("Connected");
  } catch (MqttException e) {
    logger.error("Failed to connect to MQTT client ( " + broker + "/" + clientId
        + ") for outbound messages");
    logger.error(e.getLocalizedMessage());
    e.printStackTrace();
  }
}
 
開發者ID:edgexfoundry,項目名稱:device-mqtt,代碼行數:20,代碼來源:OutgoingSender.java

示例13: startListening

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void startListening() {
  logger.debug("Starting listening for response traffic");
  try {
    String url =
        cmdrespMqttBrokerProtocol + "://" + cmdrespMqttBroker + ":" + cmdrespMqttBrokerPort;
    client = new MqttClient(url, cmdrespMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(cmdrespMqttUser);
    connOpts.setPassword(cmdrespMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(cmdrespMqttKeepAlive);
    logger.debug("Connecting to response message broker:  " + cmdrespMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to response message broker");
    client.setCallback(this);
    client.subscribe(cmdrespMqttTopic, cmdrespMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to response message queue.  "
        + "Unable to respond to command requests.");
    e.printStackTrace();
    client = null;
  }
}
 
開發者ID:edgexfoundry,項目名稱:device-mqtt,代碼行數:24,代碼來源:CommandResponseListener.java

示例14: startListening

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
private void startListening() {
  logger.debug("Starting listening for incoming traffic");
  try {
    String url =
        incomingMqttBrokerProtocol + "://" + incomingMqttBroker + ":" + incomingMqttBrokerPort;
    client = new MqttClient(url, incomingMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(incomingMqttUser);
    connOpts.setPassword(incomingMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(incomingMqttKeepAlive);
    logger.debug("Connecting to incoming message broker:  " + incomingMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to incoming message broker");
    client.setCallback(this);
    client.subscribe(incomingMqttTopic, incomingMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to incoming message queue.");
    e.printStackTrace();
    client = null;
  }
}
 
開發者ID:edgexfoundry,項目名稱:device-mqtt,代碼行數:23,代碼來源:IncomingListener.java

示例15: close

import org.eclipse.paho.client.mqttv3.MqttException; //導入依賴的package包/類
@Override
public void close()
{
    reentrantLock.lock();
    try
    {
        stop();
        mqttClient.close();
        LOG.info(
            String.format("Client ID %s is closed and cannot be restarted.", getClientId()));
    }
    catch (MqttException ex)
    {
        LOG.error(
            String.format("Client ID %s encountered an error while closing.", getClientId()),
            ex);
    }
    finally
    {
        reentrantLock.unlock();
    }
}
 
開發者ID:christophersmith,項目名稱:summer-mqtt,代碼行數:23,代碼來源:PahoAsyncMqttClientService.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。