Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:it.haefelinger.flaka.util.HttpUpload.java

protected boolean exec(HttpMethod meth) {
    HttpClient client;// www  .ja va 2 s .  co  m
    boolean rc = false;

    /* exec http method */
    try {
        client = new HttpClient();
        settimeout(client);
        setcred(client);
        client.executeMethod(meth);
        rc = (meth.getStatusCode() / 100) == 2;
        if (rc == false) {
            setError(meth.getStatusLine().toString());
        }
    } catch (java.net.UnknownHostException ex) {
        set("errmsg", "unable to resolve host `" + ex.getMessage() + "'.");
    } catch (Exception ex) {
        setError(ex.getClass().getName() + " " + ex.getMessage());
        if (this.debug) {
            System.err.println("*** excepting seen while uploading ..");
            ex.printStackTrace(System.err);
            System.err.println("<<*>>");
        }
    }
    return rc;
}

From source file:org.apache.zeppelin.cluster.ClusterManager.java

public ClusterManager() {
    try {//ww  w .j a v  a  2  s . c  o m
        zeplServerHost = RemoteInterpreterUtils.findAvailableHostAddress();
        String clusterAddr = zconf.getClusterAddress();
        if (!StringUtils.isEmpty(clusterAddr)) {
            String cluster[] = clusterAddr.split(",");

            for (int i = 0; i < cluster.length; i++) {
                String[] parts = cluster[i].split(":");
                String clusterHost = parts[0];
                int clusterPort = Integer.valueOf(parts[1]);
                if (zeplServerHost.equalsIgnoreCase(clusterHost)) {
                    raftServerPort = clusterPort;
                }

                Node node = Node.builder().withId(cluster[i])
                        .withAddress(Address.from(clusterHost, clusterPort)).build();
                clusterNodes.add(node);
                raftAddressMap.put(MemberId.from(cluster[i]), Address.from(clusterHost, clusterPort));
                clusterMemberIds.add(MemberId.from(cluster[i]));
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.error(e.getMessage());
    } catch (SocketException e) {
        LOGGER.error(e.getMessage());
    }

}

From source file:com.cloudera.flume.handlers.hdfs.CustomDfsSink.java

public CustomDfsSink(String path, OutputFormat format, Event event, String hiveTableName,
        String elasticSearchUrl, String elasticIndex, String elasticType, boolean runMarkerQueries) {
    LOG.info("inside CUSTOMDFSSINK: URL: " + elasticSearchUrl + " Index: " + elasticIndex + " Type: "
            + elasticType, " RunMarkerQueries: " + runMarkerQueries);

    sb = new StringBuilder();
    this.elasticSearchUrl = elasticSearchUrl;
    //    if (StringUtils.indexOf(this.elasticSearchUrl, "/", this.elasticSearchUrl.length() - 1) > -1) {
    //      elasticSearchUrl = StringUtils.replaceOnce(StringUtils.reverse(elasticSearchUrl), "/", "");
    //    }/*  ww w  .  ja v a 2 s.c  o  m*/
    this.elasticIndex = elasticIndex;
    this.elasticType = elasticType;
    this.runMarkerQueries = runMarkerQueries;

    Preconditions.checkArgument(path != null);
    Preconditions.checkArgument(format != null);
    this.path = path;
    this.localEvent = event;

    cal = Calendar.getInstance();
    cal.setTimeInMillis(localEvent.getTimestamp());
    this.format = format;
    this.writer = null;
    this.conf = FlumeConfiguration.get();
    this.hiveMarkerFolder = conf.getHiveDefaultMarkerFolder();

    if (StringUtils.isNotBlank(hiveTableName)) {
        this.hiveOutput = true;
        this.hiveTableName = hiveTableName;
        this.elasticSearchUrl = elasticSearchUrl;
        hup = new MarkerStore(hiveTableName, elasticSearchUrl, runMarkerQueries);
    }

    try {
        machineHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Error getting hostname for local machine: " + e.getMessage());
    }
}

From source file:fr.ortolang.diffusion.indexing.elastic.ElasticSearchServiceBean.java

@PostConstruct
public void init() {
    LOGGER.log(Level.INFO, "Initializing Elastic Search Service");
    try {/*from  w  ww.  jav  a 2s . c o m*/
        if (OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.ELASTIC_SEARCH_HOST) == null
                || OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.ELASTIC_SEARCH_HOST)
                        .length() == 0) {
            LOGGER.log(Level.INFO, "Elastic Search not configured, skipping initialization");
            client = null;
            return;
        }
        String[] hosts = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.ELASTIC_SEARCH_HOST)
                .split(",");
        String[] ports = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.ELASTIC_SEARCH_PORT)
                .split(",");

        if (hosts.length != ports.length) {
            throw new IllegalStateException(
                    "Elastic search configuration incorrect: host number and port number should be equal");
        }
        Settings settings = Settings.builder().put("cluster.name", "ortolang").build();
        client = new PreBuiltTransportClient(settings);
        for (int i = 0; i < hosts.length; i++) {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hosts[i]),
                    Integer.parseInt(ports[i])));
        }
    } catch (UnknownHostException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:de.nava.informa.utils.PersistChanGrpMgrTask.java

/**
 * Process items in the newly parsed Channel. If they are new (i.e. not yet persisted) then add
 * them to the Channel. Note the logXXX variables were put in to do better error reporting in the
 * event of an Exception./*  w  ww .  jav a  2s.  c  om*/
 *
 * @param chan
 * @param info -
 */
private void handleChannelItems(Channel chan, UpdateChannelInfo info) {
    ChannelIF tempChannel = null;
    int logHowManySearched = 0;
    int logHowManyAdded = 0;

    // TODO: [Aleksey Gureev] I don't see locking of builder here. Locking of the whole peice will
    // be very
    // great resource consumption. It's necessary to rework whole method to lock builder for a
    // minimal time.

    try {
        builder.beginTransaction();
        builder.reload(chan);
        /*
        * We will now parse the new channel's information into a *memory based* temporary channel. We
        * will then see which items that we received from the feed are already present and add the
        * new ones.
        */
        tempChannel = FeedParser.parse(tempBuilder, chan.getLocation());
        InformaUtils.copyChannelProperties(tempChannel, chan);
        /*
        * Tricky: this channel might have been loaded into memory by Hibernate in a preceding
        * Hibernate Session. We need to make it available in this session so it will be written back
        * to disk when the transaction is committed.
        */
        chan.setLastUpdated(new Date());
        mgr.notifyChannelRetrieved(chan);
        /*
        * Compare with the existing items, and only add new ones. In the future this is where we
        * would put code to diff an item to see how blog author has edited a certain item over time.
        */
        if (!tempChannel.getItems().isEmpty()) {
            for (ItemIF itemIF : tempChannel.getItems()) {
                logHowManySearched++;
                de.nava.informa.impl.basic.Item transientItem = (de.nava.informa.impl.basic.Item) itemIF;
                if (!chan.getItems().contains(transientItem)) {
                    LOG.info("Found new item: " + transientItem);
                    logHowManyAdded++;
                    /*
                    * A persistent item is created, using all the state from the memory based item produced
                    * by parser.
                    */
                    ItemIF newItem = builder.createItem(chan, transientItem);
                    mgr.notifyItemAdded((Item) newItem);
                }
            } // while it.hasNext()
        }
        builder.endTransaction();
    } catch (UnknownHostException e) {
        // Normal situation when user is offline
        LOG.debug("Host not found: " + e.getMessage());
    } catch (Exception e) {
        info.increaseProblemsOccurred(e);
        String msg = "Exception in handleChannelItems. # Potential new items = " + logHowManySearched
                + ", # Items actually added to channel: " + logHowManyAdded + "\n     Stored Chan=" + chan
                + "\n     ParsedChan=" + tempChannel;
        LOG.error(msg + "\n     Continue....");
    } finally {
        // If there was an exception we still will be in transaction.
        if (builder.inTransaction())
            builder.resetTransaction();
    }
}

From source file:org.openhab.binding.ntp.internal.handler.NtpHandler.java

/**
 * Queries the given timeserver <code>hostname</code> and returns the time
 * in milliseconds./* w w  w  .  j a va2s . c  o  m*/
 *
 * @param hostname the timeserver to query
 * @return the time in milliseconds or the current time of the system if an
 *         error occurs.
 */
public long getTime(String hostname) {
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress, port.intValue());
        timeInfo.computeDetails();

        long serverMillis = timeInfo.getReturnTime() + timeInfo.getOffset();
        logger.debug("{} Got time update from host '{}': {}.", getThing().getUID(), hostname,
                SDF.format(new Date(serverMillis)));
        updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
        return serverMillis;
    } catch (UnknownHostException uhe) {
        logger.debug(
                "{} The given hostname '{}' of the timeserver is unknown -> returning current sytem time instead. ({})",
                getThing().getUID(), hostname, uhe.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "@text/offline.comm-error-unknown-host [\"" + (hostname == null ? "null" : hostname) + "\"]");
    } catch (IOException ioe) {
        logger.debug(
                "{} Couldn't establish network connection to host '{}' -> returning current sytem time instead. ({})",
                getThing().getUID(), hostname, ioe.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "@text/offline.comm-error-connection [\"" + (hostname == null ? "null" : hostname) + "\"]");
    }

    return System.currentTimeMillis();
}

From source file:org.hyperic.hq.plugin.rabbitmq.detect.RabbitServerDetector.java

/**
 * Create the server name//from w  w  w  .  java2  s .c  o  m
 * @param args
 * @return rabbit@host
 */
private String getServerName(String[] args) {
    String name = null;
    for (int n = 0; n < args.length; n++) {
        if (args[n].equalsIgnoreCase(DetectorConstants.SNAME)) {
            name = args[n + 1];
        }
    }
    if ((name != null) && (!name.contains("@"))) {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostName();
            String old_name = name;
            name += "@" + hostname;
            name = name.substring(0, name.indexOf("."));
            logger.debug(DetectorConstants.SNAME + "=" + old_name + " -> " + name);
        } catch (UnknownHostException ex) {
            name = null;
            logger.debug(ex.getMessage(), ex);
        }
    }
    return name;
}

From source file:org.opennms.netmgt.snmp.snmp4j.Snmp4JValue.java

Snmp4JValue(final int syntax, final byte[] bytes) {
    switch (syntax) {
    case SMIConstants.SYNTAX_INTEGER: {
        m_value = new Integer32(new BigInteger(bytes).intValue());
        break;//from  ww  w  .  j a va 2s  .  c o  m
    }
    case SMIConstants.SYNTAX_COUNTER32: {
        m_value = new Counter32(new BigInteger(bytes).longValue());
        break;
    }
    case SMIConstants.SYNTAX_COUNTER64: {
        m_value = new Counter64(new BigInteger(bytes).longValue());
        break;
    }
    case SMIConstants.SYNTAX_TIMETICKS: {
        m_value = new TimeTicks(new BigInteger(bytes).longValue());
        break;
    }
    case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: {
        m_value = new UnsignedInteger32(new BigInteger(bytes).longValue());
        break;
    }
    case SMIConstants.SYNTAX_IPADDRESS: {
        try {
            m_value = new IpAddress(InetAddress.getByAddress(bytes));
        } catch (final UnknownHostException e) {
            throw new IllegalArgumentException("unable to create InetAddress from bytes: " + e.getMessage());
        }
        break;
    }
    case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: {
        m_value = new OID(new String(bytes));
        break;
    }
    case SMIConstants.SYNTAX_OCTET_STRING: {
        m_value = new OctetString(bytes);
        break;
    }
    case SMIConstants.SYNTAX_OPAQUE: {
        m_value = new Opaque(bytes);
        break;
    }
    case SMIConstants.EXCEPTION_END_OF_MIB_VIEW: {
        m_value = Null.endOfMibView;
        break;
    }
    case SMIConstants.EXCEPTION_NO_SUCH_INSTANCE: {
        m_value = Null.noSuchInstance;
        break;
    }
    case SMIConstants.EXCEPTION_NO_SUCH_OBJECT: {
        m_value = Null.noSuchObject;
        break;
    }
    case SMIConstants.SYNTAX_NULL: {
        m_value = new Null();
        break;
    }
    default:
        throw new IllegalArgumentException("invalid syntax " + syntax);
    }
    if (m_value == null) {
        throw new IllegalArgumentException("value object created from syntax " + syntax + " is null");
    }

}

From source file:org.apache.marmotta.platform.security.services.SecurityServiceImpl.java

/**
 * Parse host patterns into subnet information. A host pattern has one of the following forms:
 * <ul>/*from   w  ww . j a  va2 s .  c om*/
 *     <li>LOCAL, meaning all local interfaces</li>
 *     <li>x.x.x.x/yy, meaning an IPv4 CIDR address with netmask (number of bits significant for the network, max 32), e.g. 192.168.100.0/24 </li>
 *     <li>xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/yy, meaning an IPv6 CIDR address with netmask (prefix length, max 128)</li>
 * </ul>
 * @param hostPatternStrings
 * @return
 */
private Set<SubnetInfo> parseHostAddresses(List<String> hostPatternStrings) {
    HashSet<SubnetInfo> hostPatterns = new HashSet<SubnetInfo>();
    for (String host : hostPatternStrings) {
        try {
            // reserved name: LOCAL maps to all local addresses
            if ("LOCAL".equalsIgnoreCase(host)) {
                try {
                    Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
                    while (ifs.hasMoreElements()) {
                        NetworkInterface iface = ifs.nextElement();
                        Enumeration<InetAddress> addrs = iface.getInetAddresses();
                        while (addrs.hasMoreElements()) {
                            InetAddress addr = addrs.nextElement();

                            try {
                                hostPatterns.add(SubnetInfo.getSubnetInfo(addr));
                            } catch (UnknownHostException e) {
                                log.warn("could not parse interface address: {}", e.getMessage());
                            }

                        }
                    }
                } catch (SocketException ex) {
                    log.warn("could not determine local IP addresses, will use 127.0.0.1/24");

                    try {
                        hostPatterns.add(SubnetInfo.getSubnetInfo("127.0.0.1/24")); // IPv4
                        hostPatterns.add(SubnetInfo.getSubnetInfo("::1/128")); // IPv6
                    } catch (UnknownHostException e) {
                        log.error("could not parse localhost address: {}", e.getMessage());
                    }
                }
            } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\./[0-9]+$")) {
                // CIDR notation
                try {
                    hostPatterns.add(SubnetInfo.getSubnetInfo(host));
                } catch (UnknownHostException e) {
                    log.warn("could not parse host specification '{}': {}", host, e.getMessage());
                }

            } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$")) {
                // IP address
                try {
                    hostPatterns.add(SubnetInfo.getSubnetInfo(host + "/32"));
                } catch (UnknownHostException e) {
                    log.warn("could not parse host specification '{}': {}", host, e.getMessage());
                }

            } else if (IPAddressUtil.isIPv6LiteralAddress(host)) {
                // IPv6 address
                try {
                    hostPatterns.add(SubnetInfo.getSubnetInfo(host));
                } catch (UnknownHostException e) {
                    log.warn("could not parse host specification '{}': {}", host, e.getMessage());
                }

            } else {
                log.warn(
                        "invalid host name specification: {}; please use either CIDR u.v.w.x/zz notation or the keyword LOCAL",
                        host);
            }
        } catch (IllegalArgumentException ex) {
            log.warn("illegal host specification for security constraint {}; not in CIDR notation!", host);
        }
    }
    return hostPatterns;
}

From source file:com.clustercontrol.winservice.util.RequestWinRM.java

/**
 * WinRM????Windows??Running??????/*from   w ww  .j av  a2 s. c o  m*/
 * 
 * @param ipAddress
 * @param user
 * @param userPassword
 * @param port
 * @param protocol
 * @param timeout
 * @param retries
 * @return
 */
public boolean polling(String ipAddress, String user, String userPassword, int port, String protocol,
        int timeout, int retries) throws HinemosUnknown, WsmanException {
    m_log.debug("polling() " + "ipAddress = " + ipAddress + ",user = " + user + ",userPassword = "
            + userPassword + ",port = " + port + ",protocol = " + protocol + ",timeout = " + timeout
            + ",retries = " + retries);

    // XML?TransformerFactory?
    m_log.debug("polling() javax.xml.transform.TransformerFactory = "
            + System.getProperty("javax.xml.transform.TransformerFactory"));
    System.setProperty("javax.xml.transform.TransformerFactory",
            "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");

    // URL??
    try {
        InetAddress address = InetAddress.getByName(ipAddress);
        if (address instanceof Inet6Address) {
            m_url = protocol + "://[" + ipAddress + "]:" + port + "/wsman";
        } else {
            m_url = protocol + "://" + ipAddress + ":" + port + "/wsman";
        }
    } catch (UnknownHostException e) {
        m_log.info("polling() ipAddress is not valid : " + ipAddress + e.getClass().getSimpleName() + ", "
                + e.getMessage());
        throw new HinemosUnknown("ipAddress is not valid : " + ipAddress);
    }
    m_log.debug("polling() url = " + m_url);

    // ????
    m_con = WsmanConnection.createConnection(m_url);
    m_con.setAuthenticationScheme("basic");
    m_con.setUsername(user);
    m_con.setUserpassword(userPassword);
    m_con.setTimeout(timeout);

    boolean sslTrustall = HinemosPropertyUtil.getHinemosPropertyBool("monitor.winservice.ssl.trustall", true);
    if (sslTrustall) {
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };

        m_con.setTrustManager(tm);
        m_con.setHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    } else {
        // HTTP???? common-httpclient ? HostnameVerifier ?
        m_con.setHostnameVerifier(SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    // URI?
    ManagedReference ref = m_con.newReference(URI_WIN32_SERVICE);
    ref.addSelector("Name", m_serviceName);

    // 
    int count = 0;
    WsmanException lastException = null;
    while (count < retries) {
        try {
            // 
            ManagedInstance inst = ref.get();
            if (m_log.isDebugEnabled()) {
                m_log.debug(WsmanUtils.getXML(inst));
            }

            // ??
            Object stateObj = inst.getProperty("State");
            if (stateObj != null) {
                m_state = stateObj.toString();
            } else {
                count++;
                continue;
            }

            // ?
            if (STATE_RUNNING.equalsIgnoreCase(m_state)) {

                // [OK]
                m_message = m_serviceName + " Service is " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is " + STATE_RUNNING;
                m_date = HinemosTime.currentTimeMillis();

                break;
            } else {
                // [NG]
                m_message = m_serviceName + " Service is not " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is another state : " + m_state;
                m_date = HinemosTime.currentTimeMillis();

                return false;
            }

        } catch (WsmanException e) {
            m_log.debug("polling() url=" + m_url + ", count=" + count + " " + e.getMessage() + ", "
                    + e.getReason());

            lastException = e; // ??
            count++;
            continue;

        } finally {

            if (m_con != null) {
                m_con = null;
            }
        }
    }

    // ???NG
    if (count == retries) {

        // ?
        m_message = "WinRM Access Error . ";
        m_messageOrg = "WinRM Access Error . ";
        if (lastException != null) {
            m_messageOrg = m_messageOrg + " : " + lastException.getMessage();
        }
        m_date = HinemosTime.currentTimeMillis();

        if (lastException != null) {
            m_log.info("winservice url=" + m_url + ", message=" + lastException.getMessage() + ", reason="
                    + lastException.getReason());
            if (lastException.getMessage() == null) {
                throw new HinemosUnknown(
                        MessageConstant.MESSAGE_WINSERVICE_NAME_NOT_EXIST_OR_NOT_REFERENCE_AUTHORITY_TO_WINRM
                                .getMessage() + " : " + lastException.getReason());
            } else {
                if (lastException.getMessage().indexOf("HTTP response code: 401") != -1) {
                    throw new HinemosUnknown(
                            MessageConstant.MESSAGE_FAIL_AT_WINRM_ID_OR_PASSWORD_OR_LOGINAUTH_ERR.getMessage());
                }
            }
            throw lastException;
        } else {
            // ??????????
            throw new HinemosUnknown("winservice unknown");
        }
    }

    // [OK]?????
    return true;
}