org.apache.log4j.spi.ErrorCode#java.net.UnknownHostException源码实例Demo

下面列出了org.apache.log4j.spi.ErrorCode#java.net.UnknownHostException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: apiman   文件: ErrorHandler.java
/**
 * This method handles a connection error that was caused while connecting the gateway to the backend.
 *
 * @param error the connection error to be handled
 * @return a new ConnectorException
 */
public static ConnectorException handleConnectionError(Throwable error) {
    ConnectorException ce = null;
    if (error instanceof UnknownHostException || error instanceof ConnectException || error instanceof NoRouteToHostException) {
        ce = new ConnectorException("Unable to connect to backend", error); //$NON-NLS-1$
        ce.setStatusCode(502); // BAD GATEWAY
    } else if (error instanceof InterruptedIOException || error instanceof java.util.concurrent.TimeoutException) {
        ce = new ConnectorException("Connection to backend terminated" + error.getMessage(), error); //$NON-NLS-1$
        ce.setStatusCode(504); // GATEWAY TIMEOUT

    }
    if (ce != null) {
        return ce;
    } else {
        return new ConnectorException(error.getMessage(), error);
    }
}
 
源代码2 项目: JavaWeb   文件: LoginOpenController.java
@GetMapping(value="/getHostInfo",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String getHostInfo(HttpServletRequest request,
						  HttpServletResponse response){
	JSONObject jo = new JSONObject();
	String path = request.getContextPath();
	String basePath = null;
	try {
		InetAddress addr = InetAddress.getLocalHost();
		basePath = request.getScheme()+"://"+addr.getHostAddress()+":"+request.getServerPort()+path+"/";
	} catch (UnknownHostException e) {
		basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	} 
	jo.put("host", basePath);
	return jo.toString();
}
 
源代码3 项目: mobilecloud-15   文件: EasyHttpClient.java
/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
 *      java.lang.String, int, java.net.InetAddress, int,
 *      org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock, String host, int port,
		InetAddress localAddress, int localPort, HttpParams params)
		throws IOException, UnknownHostException, ConnectTimeoutException {
	int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
	int soTimeout = HttpConnectionParams.getSoTimeout(params);

	InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
	SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

	if ((localAddress != null) || (localPort > 0)) {
		// we need to bind explicitly
		if (localPort < 0) {
			localPort = 0; // indicates "any"
		}
		InetSocketAddress isa = new InetSocketAddress(localAddress,
				localPort);
		sslsock.bind(isa);
	}

	sslsock.connect(remoteAddress, connTimeout);
	sslsock.setSoTimeout(soTimeout);
	return sslsock;
}
 
public void start() throws TTransportException, UnknownHostException {
    InetAddress inetAddress = InetAddress.getByName(hostName);

    TSSLTransportFactory.TSSLTransportParameters params =
            new TSSLTransportFactory.TSSLTransportParameters();
    params.setKeyStore(keyStore, keyStorePassword);

    TServerSocket serverTransport;

    serverTransport = TSSLTransportFactory.getServerSocket(port, clientTimeout, inetAddress, params);


    AuthenticatorService.Processor<AuthenticatorServiceImpl> processor =
            new AuthenticatorService.Processor<AuthenticatorServiceImpl>(
                    new AuthenticatorServiceImpl(thriftAuthenticatorService));
    authenticationServer = new TThreadPoolServer(
            new TThreadPoolServer.Args(serverTransport).processor(processor));
    Thread thread = new Thread(new ServerRunnable(authenticationServer));
    if (log.isDebugEnabled()) {
        log.debug("Thrift Authentication Service started at ssl://" + hostName + ":" + port);
    }
    thread.start();
}
 
源代码5 项目: JRakNet   文件: RakNet.java
/**
 * Parses a single String as an address and port and converts it to an
 * <code>InetSocketAddress</code>.
 * 
 * @param address
 *            the address to convert.
 * @param defaultPort
 *            the default port to use if one is not.
 * @return the parsed <code>InetSocketAddress</code>.
 * @throws UnknownHostException
 *             if the address is in an invalid format or if the host cannot
 *             be found.
 */
public static InetSocketAddress parseAddress(String address, int defaultPort) throws UnknownHostException {
	String[] addressSplit = address.split(":");
	if (addressSplit.length == 1 || addressSplit.length == 2) {
		InetAddress inetAddress = InetAddress.getByName(!addressSplit[0].startsWith("/") ? addressSplit[0]
				: addressSplit[0].substring(1, addressSplit[0].length()));
		int port = (addressSplit.length == 2 ? parseIntPassive(addressSplit[1]) : defaultPort);
		if (port >= 0x0000 && port <= 0xFFFF) {
			return new InetSocketAddress(inetAddress, port);
		} else {
			throw new UnknownHostException("Port number must be between 0-65535");
		}
	} else {
		throw new UnknownHostException("Format must follow address:port");
	}
}
 
源代码6 项目: jdk8u-dev-jdk   文件: HostAddresses.java
public InetAddress[] getInetAddresses() {

        if (addresses == null || addresses.length == 0)
            return null;

        ArrayList<InetAddress> ipAddrs = new ArrayList<>(addresses.length);

        for (int i = 0; i < addresses.length; i++) {
            try {
                if ((addresses[i].addrType == Krb5.ADDRTYPE_INET) ||
                    (addresses[i].addrType == Krb5.ADDRTYPE_INET6)) {
                    ipAddrs.add(addresses[i].getInetAddress());
                }
            } catch (java.net.UnknownHostException e) {
                // Should not happen since IP address given
                return null;
            }
        }

        InetAddress[] retVal = new InetAddress[ipAddrs.size()];
        return ipAddrs.toArray(retVal);

    }
 
源代码7 项目: android_9.0.0_r45   文件: NetworkMonitor.java
@Override
public InetAddress[] getAllByName(String host) throws UnknownHostException {
    // Always bypass Private DNS.
    final List<InetAddress> addrs = Arrays.asList(
            ResolvUtil.blockingResolveAllLocally(this, host));

    // Ensure the address family of the first address is tried first.
    LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>();
    addressByFamily.put(addrs.get(0).getClass(), addrs.get(0));
    Collections.shuffle(addrs);

    for (InetAddress addr : addrs) {
        addressByFamily.put(addr.getClass(), addr);
    }

    return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]);
}
 
@Test
public void testBadSslConfiguration()
    throws UnknownHostException {
  Properties props = new Properties();
  props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_INDEX_NAME, "test");
  props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_INDEX_TYPE, "test");
  props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_TYPEMAPPER_CLASS,
      AvroGenericRecordTypeMapper.class.getCanonicalName());
  props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_ID_MAPPING_ENABLED, "true");
  props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_SSL_ENABLED, "true");
  Config config = ConfigFactory.parseProperties(props);
  try {
    new ElasticsearchTransportClientWriter(config);
    Assert.fail("Writer should not be constructed");
  }
  catch (Exception e) {
  }
}
 
源代码9 项目: openhab1-addons   文件: NtpBinding.java
/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds.
 *
 * @param hostname the timeserver to query
 * @return the time in milliseconds or the current time of the system if an
 *         error occurs.
 */
protected static long getTime(String hostname) {

    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);

        return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
        logger.warn("the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead",
                hostname);
    } catch (IOException ioe) {
        logger.warn("couldn't establish network connection [host '{}'] -> returning current sytem time instead",
                hostname);
    }

    return System.currentTimeMillis();
}
 
源代码10 项目: ovsdb   文件: HwvtepDataChangeListener.java
private void disconnect(Collection<DataTreeModification<Node>> changes) {
    for (DataTreeModification<Node> change : changes) {
        final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
        final DataObjectModification<Node> mod = change.getRootNode();
        Node deleted = getRemoved(mod);
        if (deleted != null) {
            HwvtepGlobalAugmentation hgDeleted = deleted.augmentation(HwvtepGlobalAugmentation.class);
            if (hgDeleted != null) {
                try {
                    hcm.disconnect(hgDeleted);
                    hcm.stopConnectionReconciliationIfActive(key, hgDeleted);
                } catch (UnknownHostException e) {
                    LOG.warn("Failed to disconnect HWVTEP Node", e);
                }
            }
        }
    }
}
 
源代码11 项目: L.TileLayer.Cordova   文件: RouteSelector.java
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
  socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

  String socketHost;
  if (proxy.type() == Proxy.Type.DIRECT) {
    socketHost = uri.getHost();
    socketPort = getEffectivePort(uri);
  } else {
    SocketAddress proxyAddress = proxy.address();
    if (!(proxyAddress instanceof InetSocketAddress)) {
      throw new IllegalArgumentException(
          "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
    }
    InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
    socketHost = proxySocketAddress.getHostName();
    socketPort = proxySocketAddress.getPort();
  }

  // Try each address for best behavior in mixed IPv4/IPv6 environments.
  socketAddresses = dns.getAllByName(socketHost);
  nextSocketAddressIndex = 0;
}
 
public static Socket createSocket(final SocketTask task, int timeout)
 throws IOException, UnknownHostException, ConnectTimeoutException
{
        try {
            TimeoutController.execute(task, timeout);
        } catch (TimeoutController.TimeoutException e) {
            throw new ConnectTimeoutException(
                "The host did not accept the connection within timeout of " 
                + timeout + " ms");
        }
        Socket socket = task.getSocket();
        if (task.exception != null) {
            throw task.exception;
        }
        return socket;
}
 
源代码13 项目: bonita-studio   文件: PostBDMEventHandler.java
private void execute(final Event event) {
    final String fileContent = (String) event.getProperty(FILE_CONTENT);
    Map<String, String> content = new HashMap<>();
    content.put("bdmXml", fileContent);
    try {
        new ClientResource(String.format("http://%s:%s/bdm",
                InetAddress.getByName(null).getHostAddress(),
                InstanceScope.INSTANCE.getNode(BonitaStudioPreferencesPlugin.PLUGIN_ID)
                        .get(BonitaPreferenceConstants.DATA_REPOSITORY_PORT, "-1")))
                                .post(new JacksonRepresentation<Object>(content));
        BonitaStudioLog.info("BDM has been publish into Data Repository service", UIDesignerPlugin.PLUGIN_ID);
    } catch (ResourceException | UnknownHostException e) {
        BonitaStudioLog.error("An error occured while publishing the BDM into Data Repository service", e);
    }
    
}
 
源代码14 项目: Hive2Hive   文件: ConnectionTest.java
@Test
public void testConnectDisconnect() throws UnknownHostException {
	NetworkManager nodeA = new NetworkManager(new H2HDummyEncryption(), serializer, new TestFileConfiguration());
	NetworkManager nodeB = new NetworkManager(new H2HDummyEncryption(), serializer, new TestFileConfiguration());

	INetworkConfiguration netConfigA = NetworkConfiguration.createInitial("nodeA");
	INetworkConfiguration netConfigB = NetworkConfiguration.create("nodeB", InetAddress.getLocalHost());
	try {
		nodeA.connect(netConfigA);
		nodeB.connect(netConfigB);

		assertTrue(nodeB.disconnect(false));
		assertTrue(nodeB.connect(netConfigB));
	} finally {
		nodeA.disconnect(false);
		nodeB.disconnect(false);
	}
}
 
源代码15 项目: FastLib   文件: FastRetryWhen.java
/**
 * Applies this function to the given argument.
 *
 * @param observable the function argument
 * @return the function result
 */
@Override
public Observable<?> apply(Observable<? extends Throwable> observable) {
    return observable.flatMap(new Function<Throwable, ObservableSource<?>>() {
        @Override
        public ObservableSource<?> apply(Throwable throwable) {
            //未连接网络直接返回异常
            if (!NetworkUtil.isConnected(mContext)) {
                return Observable.error(throwable);
            }
            //仅仅对连接失败相关错误进行重试
            if (throwable instanceof ConnectException
                    || throwable instanceof UnknownHostException
                    || throwable instanceof SocketTimeoutException
                    || throwable instanceof SocketException
                    || throwable instanceof TimeoutException) {
                if (++mRetryCount <= mRetryMaxTime) {
                    LoggerManager.e(TAG, "网络请求错误,将在 " + mRetryDelay + " ms后进行重试, 重试次数 " + mRetryCount + ";throwable:" + throwable);
                    return Observable.timer(mRetryDelay, TimeUnit.MILLISECONDS);
                }
            }
            return Observable.error(throwable);
        }
    });
}
 
源代码16 项目: rocketmq   文件: AdminBrokerProcessor.java
private RemotingCommand consumeMessageDirectly(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final ConsumeMessageDirectlyResultRequestHeader requestHeader = (ConsumeMessageDirectlyResultRequestHeader)request
        .decodeCommandCustomHeader(ConsumeMessageDirectlyResultRequestHeader.class);

    request.getExtFields().put("brokerName", this.brokerController.getBrokerConfig().getBrokerName());
    SelectMappedBufferResult selectMappedBufferResult = null;
    try {
        MessageId messageId = MessageDecoder.decodeMessageId(requestHeader.getMsgId());
        selectMappedBufferResult = this.brokerController.getMessageStore().selectOneMessageByOffset(messageId.getOffset());

        byte[] body = new byte[selectMappedBufferResult.getSize()];
        selectMappedBufferResult.getByteBuffer().get(body);
        request.setBody(body);
    } catch (UnknownHostException e) {
    } finally {
        if (selectMappedBufferResult != null) {
            selectMappedBufferResult.release();
        }
    }

    return this.callConsumer(RequestCode.CONSUME_MESSAGE_DIRECTLY, request, requestHeader.getConsumerGroup(),
        requestHeader.getClientId());
}
 
源代码17 项目: onos   文件: OspfInterfaceChannelHandlerTest.java
/**
 * Utility for test method.
 */
private OspfInterfaceImpl createOspfInterface1() throws UnknownHostException {
    ospfInterface = new OspfInterfaceImpl();
    OspfAreaImpl ospfArea = new OspfAreaImpl();
    OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
            OspfInterfaceChannelHandler.class);
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, ip4Address5,
                              ip4Address6, 2, topologyForDeviceAndLink);
    ospfNbr.setState(OspfNeighborState.FULL);
    ospfNbr.setNeighborId(ip4Address7);
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setIpAddress(ip4Address5);
    ospfInterface.setIpNetworkMask(subnetAddress);
    ospfInterface.setBdr(ip4Address4);
    ospfInterface.setDr(ip4Address4);
    ospfInterface.setHelloIntervalTime(20);
    ospfInterface.setInterfaceType(2);
    ospfInterface.setReTransmitInterval(2000);
    ospfInterface.setMtu(6500);
    ospfInterface.setRouterDeadIntervalTime(1000);
    ospfInterface.setRouterPriority(1);
    ospfInterface.setInterfaceType(1);
    ospfInterface.addNeighbouringRouter(ospfNbr);
    return ospfInterface;
}
 
源代码18 项目: play-mpc   文件: MpdMonitor.java
private MpdMonitor() throws UnknownHostException, MPDConnectionException
{
	Configuration config = Play.application().configuration();

	String hostname = config.getString("mpd.hostname");
	int port = config.getInt("mpd.port");
	String password = config.getString("mpd.password");
	int timeout = config.getInt("mpd.timeout", 10) * 1000;
	
	Logger.info("Connecting to MPD");
	
	mpd = new MPD(hostname, port, password, timeout);
	monitor = new MPDStandAloneMonitor(mpd, 1000);
	
	thread = new Thread(monitor);
	thread.start();
}
 
@Override
public List<InetSocketAddress> getInetSocketAddresses(String itemName) {
    List<InetSocketAddress> theList = new ArrayList<InetSocketAddress>();
    ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
    if (config != null) {
        for (Command command : config.keySet()) {
            InetSocketAddress anAddress = null;
            try {
                anAddress = new InetSocketAddress(InetAddress.getByName(config.get(command).getHost()),
                        Integer.parseInt(config.get(command).getPort()));
            } catch (UnknownHostException e) {
                logger.warn("Could not resolve the hostname {} for item {}", config.get(command).getHost(),
                        itemName);
            }
            theList.add(anAddress);
        }
    }
    return theList;
}
 
源代码20 项目: datacollector   文件: HBaseConnectionHelper.java
static void validateQuorumConfigs(
    List<Stage.ConfigIssue> issues,
    Stage.Context context,
    String hbaseName,
    String zookeeperQuorum,
    String zookeeperParentZNode,
    int clientPort
) {
  if (zookeeperQuorum == null || zookeeperQuorum.isEmpty()) {
    issues.add(context.createConfigIssue(hbaseName, "zookeeperQuorum", Errors.HBASE_04));
  } else {
    List<String> zkQuorumList = Lists.newArrayList(Splitter.on(",")
                                                           .trimResults()
                                                           .omitEmptyStrings()
                                                           .split(zookeeperQuorum));
    for (String hostName : zkQuorumList) {
      try {
        InetAddress.getByName(hostName);
      } catch (UnknownHostException ex) {
        LOG.warn(Utils.format("Cannot resolve host: '{}' from zookeeper quorum '{}', error: '{}'",
            hostName,
            zookeeperQuorum,
            ex
        ), ex);
        issues.add(context.createConfigIssue(hbaseName, "zookeeperQuorum", Errors.HBASE_39, hostName));
      }
    }
  }
  if (zookeeperParentZNode == null || zookeeperParentZNode.isEmpty()) {
    issues.add(context.createConfigIssue(hbaseName, "zookeeperBaseDir", Errors.HBASE_09));
  }
  if (clientPort == 0) {
    issues.add(context.createConfigIssue(hbaseName, "clientPort", Errors.HBASE_13));

  }
}
 
protected String buildTextMessage(Throwable t)
{
    StringBuffer result        = new StringBuffer();
    String       timeOfFailure = (new Date()).toString();
    String       hostName      = null;
    String       ipAddress     = null;

    try
    {
        hostName  = InetAddress.getLocalHost().getHostName();
        ipAddress = InetAddress.getLocalHost().getHostAddress();
    }
    catch (UnknownHostException uhe)
    {
        hostName  = "unknown";
        ipAddress = "unknown";
    }

    result.append("\nTime of failure:             " + timeOfFailure);
    result.append("\nHost where failure occurred: " + hostName + " (" + ipAddress + ")");
    
    if (t != null)
    {
        result.append("\nRoot exception:");
        result.append(renderExceptionStackAsText(t));
    }
    else
    {
        result.append("\nNo exception was provided.");
    }

    return(result.toString());
}
 
源代码22 项目: CapturePacket   文件: NativeResolver.java
@Override
public Collection<InetAddress> resolveRemapped(String remappedHost) {
    try {
        Collection<InetAddress> addresses = Arrays.asList(InetAddress.getAllByName(remappedHost));

        return addresses;
    } catch (UnknownHostException e) {
        return Collections.emptyList();
    }
}
 
源代码23 项目: hawkular-metrics   文件: JobSchedulingTest.java
@BeforeClass
public void initClass() {
    try {
        jobScheduler = new SchedulerImpl(rxSession, InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}
 
源代码24 项目: hadoop   文件: TestFileCreation.java
/** Same test but the client should bind to a local interface */
@Test
public void testFileCreationSetLocalInterface() throws IOException {
  assumeTrue(System.getProperty("os.name").startsWith("Linux"));

  // The mini cluster listens on the loopback so we can use it here
  checkFileCreation("lo", false);

  try {
    checkFileCreation("bogus-interface", false);
    fail("Able to specify a bogus interface");
  } catch (UnknownHostException e) {
    assertEquals("No such interface bogus-interface", e.getMessage());
  }
}
 
源代码25 项目: uyuni   文件: HostPortValidator.java
/**
 * Validate IP address format for a given string.
 * @param ipString
 * @return true if the given string is a valid IP, else false.
 */
private boolean isValidIP(String ipString) {
    boolean ret = false;
    if (ipString != null && !ipString.isEmpty()) {
        try {
            InetAddress.getByName(ipString);
            ret = true;
        }
        catch (UnknownHostException e) {
            // Stay silent
        }
    }
    return ret;
}
 
源代码26 项目: bluemix-parking-meter   文件: Address.java
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
    List<String> transports) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
  if (transports == null) throw new IllegalArgumentException("transports == null");
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.authenticator = authenticator;
  this.transports = Util.immutableList(transports);
}
 
源代码27 项目: PgBulkInsert   文件: NumericArrayTypesTest.java
@Test
public void saveAll_NumericArray_Test() throws SQLException, UnknownHostException {

    // Create the Entity to insert:
    ArrayEntity entity = new ArrayEntity();

    entity.bigDecimalArray = Arrays.asList(
            new BigDecimal("210000.00011234567"),
            new BigDecimal("310000.00011234567")
    );

    testArrayInternal("col_numeric_array", entity, entity.bigDecimalArray, x -> x);
}
 
源代码28 项目: jeecg-cloud   文件: JeecgSystemApplication.java
public static void main(String[] args) throws UnknownHostException {

    ConfigurableApplicationContext application = SpringApplication.run(JeecgSystemApplication.class, args);
    Environment env = application.getEnvironment();
    String ip = InetAddress.getLocalHost().getHostAddress();
    String port = env.getProperty("server.port");
    log.info("\n----------------------------------------------------------\n\t" +
        "Application Jeecg-Boot is running! Access URLs:\n\t" +
        "Local: \t\thttp://localhost:" + port  + "/\n\t" +
        "External: \thttp://" + ip + ":" + port  + "/\n\t" +
        "Swagger-UI: \t\thttp://" + ip + ":" + port  + "/doc.html\n" +
        "----------------------------------------------------------");

  }
 
源代码29 项目: openhab1-addons   文件: ReadRegistersTestCase.java
/**
 * Test reading of input/holding registers, uses valuetype=int16
 */
@Test
public void testReadRegistersInt16()
        throws InterruptedException, UnknownHostException, BindingConfigParseException, ConfigurationException,
        InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // Modbus server ("modbus slave") has input registers
    addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(2));
    addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(-4));
    addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(99));

    binding = new ModbusBinding();
    binding.updated(addSlave(newLongPollBindingConfig(), SLAVE_NAME, type, ModbusBindingProvider.VALUE_TYPE_INT16,
            nonZeroOffset ? 1 : 0, 2));
    configureNumberItemBinding(2, SLAVE_NAME, 0);
    binding.execute();

    // Give the system some time to make the expected connections & requests
    waitForConnectionsReceived(1);
    waitForRequests(1);

    verify(eventPublisher, never()).postCommand(null, null);
    verify(eventPublisher, never()).sendCommand(null, null);

    if (nonZeroOffset) {
        verify(eventPublisher).postUpdate("Item1", new DecimalType(-4));
        verify(eventPublisher).postUpdate("Item2", new DecimalType(99));
    } else {
        verify(eventPublisher).postUpdate("Item1", new DecimalType(2));
        verify(eventPublisher).postUpdate("Item2", new DecimalType(-4));
    }
    verifyNoMoreInteractions(eventPublisher);
}
 
源代码30 项目: Android-Bridge-App   文件: BridgeActivity.java
private void setupWSConnectionManager() {
    try {
        WSConnectionManager.setupInstance(WEB_SOCKET_PORT);
    } catch (UnknownHostException e) {
        //Crashlytics.logException(e);
        //e.printStackTrace();
        //Log.e(TAG,e.getMessage());
    }
}