Example usage for java.net UnknownHostException printStackTrace

List of usage examples for java.net UnknownHostException printStackTrace

Introduction

In this page you can find the example usage for java.net UnknownHostException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:mvm.rya.mongodb.MongoDBRyaDAO.java

public void initConnection() throws RyaDAOException {
    try {//from  w w w.j  av  a2s  .  c om
        boolean useMongoTest = conf.getUseTestMongo();
        if (useMongoTest) {
            testsFactory = MongodForTestsFactory.with(Version.Main.PRODUCTION);
            mongoClient = testsFactory.newMongo();
            int port = mongoClient.getServerAddressList().get(0).getPort();
            conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, Integer.toString(port));
        } else {
            ServerAddress server = new ServerAddress(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE),
                    Integer.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT)));
            if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) {
                MongoCredential cred = MongoCredential.createCredential(
                        conf.get(MongoDBRdfConfiguration.MONGO_USER),
                        conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME),
                        conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD).toCharArray());
                mongoClient = new MongoClient(server, Arrays.asList(cred));
            } else {
                mongoClient = new MongoClient(server);
            }
        }
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.connectsdk.discovery.provider.ZeroconfDiscoveryProvider.java

public ZeroconfDiscoveryProvider(Context context) {
    foundServices = new ConcurrentHashMap<String, ServiceDescription>(8, 0.75f, 2);

    serviceListeners = new CopyOnWriteArrayList<DiscoveryProviderListener>();
    serviceFilters = new ArrayList<JSONObject>();

    try {/*from  w  ww .j a  v a 2s  .co m*/
        srcAddress = Util.getIpAddress(context);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.nifi.processors.rt.DeviceRegistryReportingTask.java

private NiFiDevice populateNetworkingInfo(NiFiDevice device) {

    InetAddress ip;/*from   w  ww .j av a  2 s.  com*/
    try {

        ip = InetAddress.getLocalHost();

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        //Check this isn't null
        if (network == null) {
            //Hail mary to try and get eth0
            getLogger().warn(
                    "Hardcoded getting network interface by ETH0 which could be the incorrect interface but others were null");
            network = NetworkInterface.getByName("eth0");
        }

        byte[] mac = network.getHardwareAddress();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
        }

        //Set the values to the device object.
        device.setDeviceId(sb.toString());
        device.setIp(ip.getHostAddress());

        String hostname = InetAddress.getLocalHost().getHostName();
        logger.error("First attempt at getting hostname: " + hostname);
        if (!StringUtils.isEmpty(hostname)) {
            device.setHostname(hostname);
        } else {
            //Try the linux approach ... could fail if hostname(1) system command is not available.
            try {
                Process process = Runtime.getRuntime().exec("hostname");
                InputStream is = process.getInputStream();

                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                hostname = writer.toString();
                if (StringUtils.isEmpty(hostname)) {
                    device.setHostname("UNKNOWN");
                } else {
                    device.setHostname(hostname);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error("Error attempting to resolve hostname", ex);
            }
        }

    } catch (UnknownHostException e) {
        e.printStackTrace();
        logger.error("Unknown host exception getting hostname", e);
    } catch (SocketException e) {
        e.printStackTrace();
        logger.error("socket exception getting hostname", e);
    }

    return device;
}

From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void startNotifications() throws Exception {

    if (uri == null)
        throw new NullPointerException("Please set the URI before starting notifications!");
    this.cbean = new ConsumerBean();
    cbean.setStatus(ConsumerStatus.STARTING);
    cbean.setName(getName());//from ww w  . ja  v a 2  s . co m
    cbean.setConsumerId(consumerId);
    cbean.setVersion(consumerVersion);
    cbean.setStartTime(System.currentTimeMillis());
    try {
        cbean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }

    System.out.println("Running events on topic " + Constants.ALIVE_TOPIC + " to notify of '" + getName()
            + "' service being available.");

    final Thread aliveThread = new Thread(new Runnable() {
        public void run() {

            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                aliveConnection = connectionFactory.createConnection();
                aliveConnection.start();

                final Session session = aliveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageProducer producer = session.createProducer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                // Here we are sending the message out to the topic
                while (isActive()) {
                    try {
                        Thread.sleep(Constants.NOTIFICATION_FREQUENCY);

                        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(cbean));
                        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

                        if (ConsumerStatus.STARTING.equals(cbean.getStatus())) {
                            cbean.setStatus(ConsumerStatus.RUNNING);
                        }

                    } catch (InterruptedException ne) {
                        break;
                    } catch (Exception neOther) {
                        neOther.printStackTrace();
                    }
                }
            } catch (Exception ne) {
                ne.printStackTrace();
                setActive(false);
            }
        }
    });
    aliveThread.setName("Alive Notification Topic");
    aliveThread.setDaemon(true);
    aliveThread.setPriority(Thread.MIN_PRIORITY);
    aliveThread.start();
}

From source file:com.miku.framelite.httpx.core.DownloadHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws Exception {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }/*from  ww w.j a v  a 2s. c  o  m*/
        if (fileLen > 0) {
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
        }
    }
    Exception cause = null;
    try {
        if (!isCancelled()) {
            HttpResponse response = client.execute(request/* , context */);
            if (!isCancelled()) {
                handleResponse(response);
            }
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
        publishProgress(UPDATE_FAILURE, e, 0, "unknownHostExceptioncan't resolve host");
        cause = e;
    } catch (IOException e) {
        e.printStackTrace();
        cause = e;
    } catch (NullPointerException e) {
        e.printStackTrace();
        // HttpClient 4.0.x ?bug
        // http://code.google.com/p/android/issues/detail?id=5255
        cause = new IOException("NPE in HttpClient" + e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        cause = e;
    }
    if (cause != null) {
        throw cause;
    }
}

From source file:com.example.nate.cloudcar.MainActivity.java

public void socketSend(final String chan, final int pos) {
    new Thread(new Runnable() {
        public void run() {
            try {
                int msgLength = chan.length();
                DatagramSocket s = new DatagramSocket();
                InetAddress local = InetAddress.getByName("192.168.10.200");
                byte[] message = chan.getBytes();
                DatagramPacket chanPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(chanPacket);/*from www .j a v  a  2  s.  c  o  m*/
                msgLength = Integer.toString(pos).length();
                message = Integer.toString(pos).getBytes();
                DatagramPacket posPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(posPacket);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    Thread.currentThread().interrupted();

}

From source file:com.yodlee.sampleapps.helper.OpenSamlHelper.java

/**
 * This function generates the response.
 *
 * @param subjects//from w  w w  . jav a2  s.c  o  m
 * @return SAMLResponse object
 * @throws SAMLException
 * @throws Exception
 */
public SAMLResponse generateResponse(String[] subjects, String issuer) throws SAMLException {
    // Get Host Information
    InetAddress address = null;
    try {
        address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
    String IPAddress = address.getHostAddress();
    String DNSAddress = address.getHostName();

    Collection statements = new ArrayList();

    // Create the SAML subject
    for (int i = 0; i < subjects.length; i++) {
        String subject = subjects[i];
        SAMLNameIdentifier nameIdentifier = new SAMLNameIdentifier(subject, null,
                SAMLNameIdentifier.FORMAT_X509);
        List confirmationMethodList = new ArrayList();
        confirmationMethodList.add(SAMLSubject.CONF_BEARER);

        SAMLSubject samlSubject = new SAMLSubject(nameIdentifier, confirmationMethodList, null, null);

        // Create the SAML Authentication Statement
        SAMLAuthenticationStatement sas = new SAMLAuthenticationStatement
        //(subject,"auth",new Date(),IPAddress,DNSAddress,null);
        (samlSubject, "password", new Date(), IPAddress, DNSAddress, null);

        statements.add(sas);
    }

    // Create the SAML Assertion
    SAMLAssertion assertion = new SAMLAssertion
    //(issuer,new Date(),new Date(),null,null,statements);
    (issuer, null, null, null, null, statements);
    Collection assertions = new ArrayList();
    assertions.add(assertion);

    // Create the SAML Response
    SAMLResponse response = null;
    response = new SAMLResponse("artifact", subjects[0], assertions, null);

    Collection dsa_certs = new ArrayList();
    for (int i = 0; i < OpenSamlHelper.certs.length; i++)
        dsa_certs.add(OpenSamlHelper.certs[i]);

    // Sign the Response
    try {
        response.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA, OpenSamlHelper.privateKey, dsa_certs);
    } catch (SAMLException e) {
        System.out.println("SAMLException.  Error signing the response.");
        e.printStackTrace();
    }
    //response.toStream( System.out);

    return response;
}

From source file:com.qubole.rubix.bookkeeper.BookKeeper.java

private void initializeClusterManager(int clusterType) {
    if (clusterManager == null || currentNodeIndex == -1) {
        synchronized (lock) {
            if (clusterManager == null || currentNodeIndex == -1) {
                try {
                    nodeName = InetAddress.getLocalHost().getCanonicalHostName();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    log.warn("Could not get nodeName", e);
                }/*from   w  w  w .  j  a  v a2  s.  c o  m*/

                if (clusterType == HADOOP2_CLUSTER_MANAGER.ordinal()) {
                    clusterManager = new Hadoop2ClusterManager();
                    clusterManager.initialize(conf);
                    nodes = clusterManager.getNodes();
                    splitSize = clusterManager.getSplitSize();
                } else if (clusterType == TEST_CLUSTER_MANAGER.ordinal()) {
                    nodes = new ArrayList<>();
                    nodes.add(nodeName);
                    splitSize = 64 * 1024 * 1024;
                }
                nodeListSize = nodes.size();
                currentNodeIndex = nodes.indexOf(nodeName);
            } else {
                nodes = clusterManager.getNodes();
            }
        }
    } else {
        nodes = clusterManager.getNodes();
    }
}

From source file:net.Downloader.java

public void run() {
    OutputStream os = null;//from  w  w  w.  j  a  v a2  s.  c om
    InputStream is = null;

    ProgressListener progressListener = new ProgressListener();
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new SSLManager() };

        // Install the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        os = new FileOutputStream(fl);
        is = conn.getInputStream();

        CountingStream dcount = new CountingStream(os);
        dcount.setListener(progressListener);

        status = "Downloading";
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);

    } catch (UnknownHostException u) {
        System.err.println("Uknown Host2");
        u.printStackTrace();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            status = "Finished";
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.msec.sink.es.ESSink.java

private void initESThreadPool() {
    serverAddresses = new InetSocketTransportAddress[serverAddressStrings.length];
    workingQueue = new ArrayBlockingQueue<ESClientThread.ESThreadRequest>(serverAddressStrings.length * 2);

    for (int i = 0; i < serverAddressStrings.length; i++) {
        String[] hostPort = serverAddressStrings[i].trim().split(":");
        String host = hostPort[0].trim();
        int port = hostPort.length == 2 ? Integer.parseInt(hostPort[1].trim()) : DEFAULT_PORT;
        try {/*from   www .j a  va2 s .c  o m*/
            serverAddresses[i] = new InetSocketTransportAddress(InetAddress.getByName(host), port);

            threadPool.submit(new ESClientThread(workingQueue, clusterName, serverAddresses[i]));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}