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:com.hs.mail.mailet.RemoteDelivery.java

private static Iterator<HostAddress> getGatewaySmtpHostAddresses(final String gateway) {
    return new Iterator<HostAddress>() {
        private Iterator<HostAddress> addresses = null;

        public boolean hasNext() {
            if (addresses == null) {
                String server = gateway;
                String port = "25";

                int idx = server.indexOf(':');
                if (idx > 0) {
                    port = server.substring(idx + 1);
                    server = server.substring(0, idx);
                }//  w ww .  j  av  a2s.  co m

                final String nextGateway = server;
                final String nextGatewayPort = port;
                try {
                    final InetAddress[] ips = DnsServer.getAllByName(nextGateway);
                    addresses = new Iterator<HostAddress>() {
                        private InetAddress[] ipAddresses = ips;
                        int i = 0;

                        public boolean hasNext() {
                            return i < ipAddresses.length;
                        }

                        public HostAddress next() {
                            return new HostAddress(nextGateway,
                                    "smtp://" + (ipAddresses[i++]).getHostAddress() + ":" + nextGatewayPort);
                        }

                        public void remove() {
                            throw new UnsupportedOperationException("remove not supported by this iterator");
                        }
                    };
                } catch (UnknownHostException uhe) {
                    logger.error("Unknown gateway host: " + uhe.getMessage().trim());
                    logger.error("This could be a DNS server error or configuration error.");
                }
            }
            return addresses != null && addresses.hasNext();
        }

        public HostAddress next() {
            return addresses != null ? addresses.next() : null;
        }

        public void remove() {
            throw new UnsupportedOperationException("remove not supported by this iterator");
        }
    };
}

From source file:com.ericsson.eif.hansoft.HansoftManager.java

/**
 * @param httpServletRequest//from   w  ww  . j  av  a2 s  .  c o  m
 * @return prefix
 */
public static String getPrefix(HttpServletRequest httpServletRequest) {
    if (httpServletRequest == null) {
        return "";
    }
    // check if IP is in list of known FocalPoints
    String ip = httpServletRequest.getRemoteAddr();
    if (ip == null) {
        ip = "";
    }

    if (ip != null && !ip.trim().equals("")) {
        if (hansoftFPs.contains(ip)) {
            return Constants.FP_FIX_PREFIX;
        }
    }

    // check if hostname is in list of known FocalPoints
    try {
        String hostname = InetAddress.getByName(ip).getHostName();
        if (hostname != null && !hostname.trim().equals("")) {
            if (hansoftFPs.contains(hostname)) {
                return Constants.FP_FIX_PREFIX;
            }
        }
    } catch (UnknownHostException e) {
        logger.error("Unknown host name: " + e.getMessage());
    }
    return "";
}

From source file:password.pwm.http.ServletHelper.java

public static String readUserHostname(final HttpServletRequest req, final PwmSession pwmSession)
        throws PwmUnrecoverableException {
    final Configuration config = ContextManager.getPwmApplication(req).getConfig();
    if (config != null && !config.readSettingAsBoolean(PwmSetting.REVERSE_DNS_ENABLE)) {
        return "";
    }//from w  w w  .j av a2 s . c  om

    final String userIPAddress = readUserIPAddress(req, pwmSession);
    try {
        return InetAddress.getByName(userIPAddress).getCanonicalHostName();
    } catch (UnknownHostException e) {
        LOGGER.trace(pwmSession,
                "unknown host while trying to compute hostname for src request: " + e.getMessage());
    }
    return "";
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * @param address//w ww. ja  va  2s  .  c  o  m
 *            the address of the file to be downloaded
 * @param localFileName
 *            the local file name (with absolute path)
 */
public static void download(String address, String localFileName) throws FileNotFoundException {
    logger.info("download file " + address + " to " + localFileName);
    OutputStream out = null;
    HttpURLConnection conn = null;
    InputStream in = null;
    try {
        URL url = new URL(address);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpURLConnection) {
            ((HttpURLConnection) conn).setInstanceFollowRedirects(false);

            int responseCode = ((HttpURLConnection) conn).getResponseCode();
            //manage most frequent error code and Gisgraphy specific one
            switch (responseCode) {
            case 509:
                throw new RuntimeException("Sorry, there is too many users connected for " + address
                        + ", this site has limmited resources, please try again later");
            case 500:
                throw new RuntimeException("Sorry, the server return an 500 status code for " + address
                        + ", an internal error has occured");
            case 404:
                throw new FileNotFoundException("Sorry, the server return an 404 status code for " + address
                        + ", the file probably not exists or the URL is not correct");
            case 302:
                throw new FileNotFoundException("Sorry, the server return an 302 status code for " + address
                        + ", the file is not at the correct URL");
            default:
                break;
            }

        }
        in = conn.getInputStream();
        out = new BufferedOutputStream(new FileOutputStream(localFileName));
        byte[] buffer = new byte[1024];
        int numRead;
        long numWritten = 0;
        while ((numRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, numRead);
            numWritten += numRead;
        }
        logger.info(localFileName + "\t" + numWritten);
    } catch (UnknownHostException e) {
        String errorMessage = "can not download " + address + " to " + localFileName + " : " + e.getMessage()
                + ". if the host exists and is reachable,"
                + " maybe this links can help : http://www.gisgraphy.com/forum/viewtopic.php?f=3&t=64 ";
        logger.warn(errorMessage);
        throw new ImporterException(errorMessage, e);
    } catch (FileNotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.warn("can not download " + address + " to " + localFileName + " : " + e.getMessage());
        throw new ImporterException(e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (IOException ioe) {
            logger.error("cannot close streams");
        }
    }
}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

/**
 * Opens a URL. It can be a simple URL or one which requires basic
 * authentication.//w w  w  .  jav  a2 s .co m
 * <p/>
 * Tries to access the given URL. If http response is either
 * {@code HttpStatus.SC_UNAUTHORIZED} or
 * {@code HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED}, asks for
 * login/password and tries to authenticate into proxy server and/or URL.
 * <p/>
 * This implementation relies on the Apache Http Client due to its
 * capabilities of proxy/http authentication. <br/>
 * Proxy configuration is determined by {@link ProxySelectorRoutePlanner} using the JVM proxy
 * settings by default.
 * <p/>
 * For more information see: <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/} <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/ProxySelectorRoutePlanner.html}
 * <p/>
 * There's a very simple realm cache implementation.
 * Login/Password for each realm are stored in a static {@link Map}.
 * Before asking the user the method verifies if the information is already
 * available in the memory cache.
 *
 * @param url                   the URL string to be opened.
 * @param needsMarkResetSupport Indicates the caller <em>must</em> have an input stream that
 *                              supports the mark/reset operations (as indicated by {@link InputStream#markSupported()}.
 *                              Implementation detail: If the original stream does not, it will be fetched and wrapped
 *                              into a {@link ByteArrayInputStream}. This can only work sanely if the resource is a
 *                              small file that can fit in memory. It also means the caller has no chance of showing
 *                              a meaningful download progress. If unsure, callers should set this to false.
 * @param monitor               {@link ITaskMonitor} to output status.
 * @param headers               An optional array of HTTP headers to use in the GET request.
 * @return Returns a {@link Pair} with {@code first} holding an {@link InputStream}
 * and {@code second} holding an {@link HttpResponse}.
 * The returned pair is never null and contains
 * at least a code; for http requests that provide them the response
 * also contains locale, headers and an status line.
 * The input stream can be null, especially in case of error.
 * The caller must only accept the stream if the response code is 200 or similar.
 * @throws IOException             Exception thrown when there are problems retrieving
 *                                 the URL or its content.
 * @throws CanceledByUserException Exception thrown if the user cancels the
 *                                 authentication dialog.
 */
@NonNull
static Pair<InputStream, HttpResponse> openUrl(@NonNull String url, boolean needsMarkResetSupport,
        @NonNull ITaskMonitor monitor, @Nullable Header[] headers) throws IOException, CanceledByUserException {

    Exception fallbackOnJavaUrlConnect = null;
    Pair<InputStream, HttpResponse> result = null;

    try {
        result = openWithHttpClient(url, monitor, headers);

    } catch (UnknownHostException e) {
        // Host in unknown. No need to even retry with the Url object,
        // if it's broken, it's broken. It's already an IOException but
        // it could use a better message.
        throw new IOException("Unknown Host " + e.getMessage(), e);

    } catch (ClientProtocolException e) {
        // We get this when HttpClient fails to accept the current protocol,
        // e.g. when processing file:// URLs.
        fallbackOnJavaUrlConnect = e;

    } catch (IOException e) {
        throw e;

    } catch (CanceledByUserException e) {
        // HTTP Basic Auth or NTLM login was canceled by user.
        throw e;

    } catch (Exception e) {
        if (DEBUG) {
            System.out.printf("[HttpClient Error] %s : %s\n", url, e.toString());
        }

        fallbackOnJavaUrlConnect = e;
    }

    if (fallbackOnJavaUrlConnect != null) {
        // If the protocol is not supported by HttpClient (e.g. file:///),
        // revert to the standard java.net.Url.open.

        try {
            result = openWithUrl(url, headers);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            if (DEBUG && !fallbackOnJavaUrlConnect.equals(e)) {
                System.out.printf("[Url Error] %s : %s\n", url, e.toString());
            }
        }
    }

    // If the caller requires an InputStream that supports mark/reset, let's
    // make sure we have such a stream.
    if (result != null && needsMarkResetSupport) {
        InputStream is = result.getFirst();
        if (is != null) {
            if (!is.markSupported()) {
                try {
                    // Consume the whole input stream and offer a byte array stream instead.
                    // This can only work sanely if the resource is a small file that can
                    // fit in memory. It also means the caller has no chance of showing
                    // a meaningful download progress.
                    InputStream is2 = toByteArrayInputStream(is);
                    if (is2 != null) {
                        result = Pair.of(is2, result.getSecond());
                        try {
                            is.close();
                        } catch (Exception ignore) {
                        }
                    }
                } catch (Exception e3) {
                    // Ignore. If this can't work, caller will fail later.
                }
            }
        }
    }

    if (result == null) {
        // Make up an error code if we don't have one already.
        HttpResponse outResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), //$NON-NLS-1$
                HttpStatus.SC_METHOD_FAILURE, ""); //$NON-NLS-1$;  // 420=Method Failure
        result = Pair.of(null, outResponse);
    }

    return result;
}

From source file:password.pwm.http.filter.RequestInitializationFilter.java

public static String readUserHostname(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
    final Configuration config = pwmRequest.getConfig();
    if (config != null && !config.readSettingAsBoolean(PwmSetting.REVERSE_DNS_ENABLE)) {
        return "";
    }/*from  ww w .  jav a  2s  .c om*/

    final String userIPAddress = readUserIPAddress(pwmRequest);
    try {
        return InetAddress.getByName(userIPAddress).getCanonicalHostName();
    } catch (UnknownHostException e) {
        LOGGER.trace(pwmRequest,
                "unknown host while trying to compute hostname for src request: " + e.getMessage());
    }
    return "";
}

From source file:org.jboss.as.test.integration.security.common.CoreUtils.java

/**
 * Replace keystore paths and passwords variables in original configuration file with given values
 * and set ${hostname} variable from system property: node0
 *
 * @return String content//from w w  w.  ja v a  2  s .c om
 */
public static String propertiesReplacer(String originalFile, String keystoreFile, String trustStoreFile,
        String keystorePassword, String vaultConfig) {
    String hostname = System.getProperty("node0");

    // expand possible IPv6 address
    try {
        hostname = NetworkUtils.formatPossibleIpv6Address(InetAddress.getByName(hostname).getHostAddress());
    } catch (UnknownHostException ex) {
        String message = "Cannot resolve host address: " + hostname + " , error : " + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    final Map<String, String> map = new HashMap<String, String>();
    String content = "";
    if (vaultConfig == null) {
        map.put("vaultConfig", "");
    } else {
        map.put("vaultConfig", vaultConfig);
    }
    map.put("hostname", hostname);
    map.put("keystore", keystoreFile);
    map.put("truststore", trustStoreFile);
    map.put("password", keystorePassword);

    try {
        content = StrSubstitutor
                .replace(IOUtils.toString(CoreUtils.class.getResourceAsStream(originalFile), "UTF-8"), map);
    } catch (IOException ex) {
        String message = "Cannot find or modify configuration file " + originalFile + " , error : "
                + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    return content;
}

From source file:nl.nn.adapterframework.util.Misc.java

public static String getHostname() {
    String localHost = null;//  w ww. j a v a 2  s  .  c om
    // String localIP="";
    try {
        InetAddress localMachine = InetAddress.getLocalHost();
        //localIP = localMachine.getHostAddress();
        localHost = localMachine.getHostName();
    } catch (UnknownHostException uhe) {
        if (localHost == null) {
            localHost = "unknown (" + uhe.getMessage() + ")";
        }
    }
    return localHost;
}

From source file:io.fabric8.che.starter.exception.GlobalExceptionHandler.java

@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "MasterUrl is not valid")
@ExceptionHandler(UnknownHostException.class)
public String handleHostException(UnknownHostException e) {
    return e.getMessage();
}

From source file:com.example.HoneycombFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    libhoney = new LibHoney.Builder().writeKey(filterConfig.getInitParameter("honeycomb.writeKey"))
            .dataSet(filterConfig.getInitParameter("honeycomb.dataSet")).build();
    try {/*from ww w  .  j a  va2 s.com*/
        libhoney.addField("server", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        log.error(e.getMessage(), e);
    }
}