Search in sources :

Example 61 with UnknownHostException

use of java.net.UnknownHostException in project NoHttp by yanzhenjie.

the class HttpConnection method getConnection.

/**
     * Send the request, send only head, parameters, such as file information.
     *
     * @param request {@link IBasicRequest}.
     * @return {@link Connection}.
     */
public Connection getConnection(IBasicRequest request) {
    Logger.d("--------------Request start--------------");
    Headers responseHeaders = new HttpHeaders();
    InputStream inputStream = null;
    Exception exception = null;
    Network network = null;
    String url = request.url();
    try {
        if (!NetUtil.isNetworkAvailable())
            throw new NetworkError("The network is not available, please check the network. The requested url is:" + " " + url);
        // MalformedURLException, IOException, ProtocolException, UnknownHostException, SocketTimeoutException
        network = createConnectionAndWriteData(request);
        Logger.d("-------Response start-------");
        int responseCode = network.getResponseCode();
        responseHeaders = parseResponseHeaders(new URI(request.url()), responseCode, network.getResponseHeaders());
        // handle body
        if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) {
            Connection redirectConnection = handleRedirect(request, responseHeaders);
            responseHeaders = redirectConnection.responseHeaders();
            inputStream = redirectConnection.serverStream();
            exception = redirectConnection.exception();
        } else if (hasResponseBody(request.getRequestMethod(), responseCode)) {
            inputStream = network.getServerStream(responseCode, responseHeaders);
        }
        Logger.d("-------Response end-------");
    } catch (MalformedURLException e) {
        exception = new URLError("The url is malformed: " + url + ".");
    } catch (UnknownHostException e) {
        exception = new UnKnownHostError("Hostname can not be resolved: " + url + ".");
    } catch (SocketTimeoutException e) {
        exception = new TimeoutError("Request time out: " + url + ".");
    } catch (Exception e) {
        exception = e;
    } finally {
        if (exception != null)
            Logger.e(exception);
    }
    Logger.d("--------------Request finish--------------");
    return new Connection(network, responseHeaders, inputStream, exception);
}
Also used : MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) HttpURLConnection(java.net.HttpURLConnection) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) URLError(com.yanzhenjie.nohttp.error.URLError) URI(java.net.URI) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SocketTimeoutException(java.net.SocketTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError)

Example 62 with UnknownHostException

use of java.net.UnknownHostException in project OpenAM by OpenRock.

the class PasswordValidator method isAgentAdminLoginValid.

/*
     * validate Agent Administrator's name and password.
     */
private ValidationResult isAgentAdminLoginValid(String passfileName, Map props, IStateAccess state) throws InstallException {
    ValidationResultStatus validRes = ValidationResultStatus.STATUS_FAILED;
    LocalizedMessage returnMessage = null;
    String agentUserName = null;
    String serverURL = null;
    String restAuthURL = null;
    String agentUserNameKey = (String) props.get(STR_AGENT_PROFILE_LOOKUP_KEY);
    if (agentUserNameKey != null) {
        agentUserName = (String) state.get(agentUserNameKey);
    }
    Map tokens = state.getData();
    if (tokens.containsKey("AM_SERVER_URL")) {
        serverURL = (String) tokens.get("AM_SERVER_URL");
    }
    String agentUserPasswd = readDataFromFile(passfileName);
    try {
        restAuthURL = serverURL + "/identity/authenticate";
        String encodingType = "UTF-8";
        String encodedPostData = "username=" + URLEncoder.encode(agentUserName, encodingType) + "&password=" + URLEncoder.encode(agentUserPasswd, encodingType) + "&uri=" + URLEncoder.encode("realm=/&module=Application", encodingType);
        RESTUtils.RESTResponse response = RESTUtils.callServiceURL(restAuthURL, encodedPostData);
        // Read response code
        int responseCode = response.getResponseCode();
        if (responseCode == HTTP_RESPONSE_OK) {
            validRes = ValidationResultStatus.STATUS_SUCCESS;
            setCreateAgentProfile(state, "true");
        } else if (responseCode == HTTP_RESPONSE_AUTHENTICATION_FAILED) {
            String responseStr = response.toString();
            if (responseStr.indexOf(STR_IDENTITY_INVALID_PASSWORD) > 0) {
                // wrong password
                returnMessage = LocalizedMessage.get(LOC_VA_WRN_IN_VAL_AGENT_PASSWORD, new Object[] { agentUserName });
            } else if (responseStr.indexOf(STR_IDENTITY_INVALID_CREDENTIALS) > 0) {
                // user does not exist.
                returnMessage = LocalizedMessage.get(LOC_VA_ERR_IN_VAL_AGENT_PROFILE_NOT_PRESENT, new Object[] { agentUserName });
            } else {
                Debug.log("PasswordValidator.isAgentAdminLoginValid() - " + "Error from OpenSSO:" + response.toString());
                returnMessage = LocalizedMessage.get(LOC_VA_ERR_IN_VAL_OTHER_AGENT_AUTH_FAILURE, new Object[] { Integer.valueOf(responseCode) });
            }
        } else {
            Debug.log("PasswordValidator.isAgentAdminLoginValid() - " + "Error from OpenSSO:" + response.toString());
            returnMessage = LocalizedMessage.get(LOC_VA_ERR_IN_VAL_AGENT_GENERIC_FAILURE, new Object[] { Integer.valueOf(responseCode) });
        }
    } catch (UnknownHostException uhe) {
        Debug.log("PasswordValidator.isAgentAdminLoginValid() " + "threw exception :", uhe);
        returnMessage = LocalizedMessage.get(LOC_VA_WRN_UN_REACHABLE_FAM_SERVER_URL, new Object[] { restAuthURL });
    } catch (ConnectException ce) {
        Debug.log("PasswordValidator.isAgentAdminLoginValid() " + "threw exception :", ce);
        returnMessage = LocalizedMessage.get(LOC_VA_WRN_UN_REACHABLE_FAM_SERVER_URL, new Object[] { restAuthURL });
    } catch (FileNotFoundException ex) {
        Debug.log("PasswordValidator.isAgentAdminLoginValid() " + "threw exception :", ex);
        returnMessage = LocalizedMessage.get(LOC_VA_WRN_NOT_FOUND_SERVER_URL, new Object[] { restAuthURL });
    } catch (IOException ex) {
        Debug.log("PasswordValidator.isAgentAdminLoginValid() " + "threw exception :", ex);
    }
    return new ValidationResult(validRes, null, returnMessage);
}
Also used : RESTUtils(com.sun.identity.install.tools.util.RESTUtils) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) LocalizedMessage(com.sun.identity.install.tools.util.LocalizedMessage) ConnectException(java.net.ConnectException)

Example 63 with UnknownHostException

use of java.net.UnknownHostException in project OpenAM by OpenRock.

the class PasswordValidator method isAgentLoginValid.

/*
     * Checks if Agent profile/User's name&password is valid.
     *
     * @param port @param props @param state
     *
     * @return ValidationResult
     */
public ValidationResult isAgentLoginValid(String passfileName, Map props, IStateAccess state) throws InstallException {
    ValidationResultStatus validRes = ValidationResultStatus.STATUS_FAILED;
    LocalizedMessage returnMessage = null;
    String agentUserName = null;
    String serverURL = null;
    String restAuthURL = null;
    String str = null;
    String serverURLValid = (String) state.get("isServerURLValid");
    String createAgentProfileKey = (String) state.get(InstallConstants.STR_CREATE_AGENT_PROFILE_KEY);
    if (createAgentProfileKey == null) {
        setCreateAgentProfile(state, "false");
    }
    if (serverURLValid != null && serverURLValid.equals("true")) {
        if (isAgentAdmin(props, state)) {
            return isAgentAdminLoginValid(passfileName, props, state);
        }
        String agentUserNameKey = (String) props.get(STR_AGENT_PROFILE_LOOKUP_KEY);
        if (agentUserNameKey != null) {
            agentUserName = (String) state.get(agentUserNameKey);
        }
        Map tokens = state.getData();
        if (tokens.containsKey("AM_SERVER_URL")) {
            serverURL = (String) tokens.get("AM_SERVER_URL");
        }
        String agentUserPasswd = readDataFromFile(passfileName);
        try {
            restAuthURL = serverURL + "/identity/authenticate";
            String encodingType = "UTF-8";
            String encodedPostData = "username=" + URLEncoder.encode(agentUserName, encodingType) + "&password=" + URLEncoder.encode(agentUserPasswd, encodingType) + "&uri=" + URLEncoder.encode("realm=/&module=Application", encodingType);
            RESTUtils.RESTResponse response = RESTUtils.callServiceURL(restAuthURL, encodedPostData);
            // Read response code
            int responseCode = response.getResponseCode();
            if (responseCode == HTTP_RESPONSE_OK) {
                validRes = ValidationResultStatus.STATUS_SUCCESS;
                setCreateAgentProfile(state, "false");
            } else if (responseCode == HTTP_RESPONSE_AUTHENTICATION_FAILED) {
                String responseStr = response.toString();
                if (responseStr.indexOf(STR_IDENTITY_INVALID_PASSWORD) > 0) {
                    // wrong password
                    returnMessage = LocalizedMessage.get(LOC_VA_WRN_IN_VAL_AGENT_PASSWORD, new Object[] { agentUserName });
                } else if (responseStr.indexOf(STR_IDENTITY_INVALID_CREDENTIALS) > 0) {
                    // create agent profile only when agent profile 
                    // does not exist.
                    setCreateAgentProfile(state, "true");
                    returnMessage = LocalizedMessage.get(LOC_VA_WRN_IN_VAL_AGENT_PROFILE_NOT_PRESENT, new Object[] { agentUserName });
                    validRes = ValidationResultStatus.STATUS_WARNING;
                } else {
                    Debug.log("PasswordValidator.isAgentLoginValid() - " + "Error from OpenSSO:" + response.toString());
                    returnMessage = LocalizedMessage.get(LOC_VA_WRN_IN_VAL_OTHER_AGENT_AUTH_FAILURE, new Object[] { Integer.valueOf(responseCode) });
                    validRes = ValidationResultStatus.STATUS_WARNING;
                }
            } else {
                Debug.log("PasswordValidator.isAgentLoginValid() - " + "Error from OpenSSO:" + response.toString());
                returnMessage = LocalizedMessage.get(LOC_VA_WRN_IN_VAL_AGENT_GENERIC_FAILURE, new Object[] { Integer.valueOf(responseCode) });
                validRes = ValidationResultStatus.STATUS_WARNING;
            }
        } catch (UnknownHostException uhe) {
            Debug.log("PasswordValidator.isAgentLoginValid() " + "threw exception :", uhe);
            returnMessage = LocalizedMessage.get(LOC_VA_WRN_UN_REACHABLE_FAM_SERVER_URL, new Object[] { restAuthURL });
            validRes = ValidationResultStatus.STATUS_WARNING;
        } catch (ConnectException ce) {
            Debug.log("PasswordValidator.isAgentLoginValid() " + "threw exception :", ce);
            returnMessage = LocalizedMessage.get(LOC_VA_WRN_UN_REACHABLE_FAM_SERVER_URL, new Object[] { restAuthURL });
            validRes = ValidationResultStatus.STATUS_WARNING;
        } catch (FileNotFoundException ex) {
            Debug.log("PasswordValidator.isAgentLoginValid() " + "threw exception :", ex);
            returnMessage = LocalizedMessage.get(LOC_VA_WRN_NOT_FOUND_SERVER_URL, new Object[] { restAuthURL });
            validRes = ValidationResultStatus.STATUS_WARNING;
        } catch (IOException ex) {
            Debug.log("PasswordValidator.isAgentLoginValid() " + "threw exception :", ex);
        }
        return new ValidationResult(validRes, null, returnMessage);
    } else {
        returnMessage = LocalizedMessage.get(LOC_VA_WRN_SERVER_URL_NOT_RUNNING, new Object[] { serverURL });
        validRes = ValidationResultStatus.STATUS_WARNING;
        return new ValidationResult(validRes, null, returnMessage);
    }
}
Also used : RESTUtils(com.sun.identity.install.tools.util.RESTUtils) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) LocalizedMessage(com.sun.identity.install.tools.util.LocalizedMessage) ConnectException(java.net.ConnectException)

Example 64 with UnknownHostException

use of java.net.UnknownHostException in project OpenAM by OpenRock.

the class CDCServlet method init.

/**
     * Initiates the servlet.
     *
     * @param config Servlet Configuration object that contains configutation
     *        information for this servlet.
     * @throws ServletException if servlet failed to initialize.
     */
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    debug.message("CDCServlet Initializing...");
    try {
        tokenManager = SSOTokenManager.getInstance();
        sessionService = InjectorHolder.getInstance(SessionService.class);
        spValidator = new LdapSPValidator();
        DNSAddress = SystemConfigurationUtil.getProperty(Constants.AM_SERVER_HOST);
        IPAddress = InetAddress.getByName(DNSAddress).getHostAddress();
        authURLCookieName = SystemConfigurationUtil.getProperty(Constants.AUTH_UNIQUE_COOKIE_NAME, UNIQUE_COOKIE_NAME);
        authURLCookieDomain = SystemConfigurationUtil.getProperty(Constants.AUTH_UNIQUE_COOKIE_DOMAIN, "");
        deployDescriptor = SystemConfigurationUtil.getProperty(Constants.AM_SERVICES_DEPLOYMENT_DESCRIPTOR, DEFAULT_DEPLOY_URI);
        // Check if CDC needs to generate restricted SSO Tokens
        uniqueCookieEnabled = Boolean.valueOf(SystemConfigurationUtil.getProperty(Constants.IS_ENABLE_UNIQUE_COOKIE, "false")).booleanValue();
        if (debug.messageEnabled()) {
            debug.message("CDCServlet init params:" + " Restricted Token Enabled = " + uniqueCookieEnabled + " Auth URL Cookie Name = " + authURLCookieName + " Auth URL Cookie Domain = " + authURLCookieDomain + " Deployment Descriptor: " + deployDescriptor);
        }
    } catch (SSOException e) {
        debug.error("CDCServlet.init: Unable to get SSOTokenManager", e);
        throw new ServletException(e.getMessage());
    } catch (UnknownHostException e) {
        debug.error("CDCServlet.init", e);
        throw new ServletException(e.getMessage());
    }
}
Also used : ServletException(javax.servlet.ServletException) SessionService(com.iplanet.dpro.session.service.SessionService) UnknownHostException(java.net.UnknownHostException) SSOException(com.iplanet.sso.SSOException)

Example 65 with UnknownHostException

use of java.net.UnknownHostException in project OpenAM by OpenRock.

the class AMSetupUtils method getRemoteServerInfo.

/**
     * Obtains misc config data from a remote OpenAM server:
     * <ul>
     *     <li>OpendDJ admin port</li>
     *     <li>config basedn</li>
     *     <li>replication ready flag</li>
     *     <li>OpenDJ replication port or OpenDJ suggested port</li>
     * </ul>
     *
     * @param serverUrl URL string representing the remote OpenAM server.
     * @param userId The admin user id on remote server, (only amadmin).
     * @param password The admin password.
     * @return A {@code Map} of config parameters.
     * @throws ConfigurationException for the following error code:
     * <ul>
     *     <li>400=Bad Request - user id/password param missing</li>
     *     <li>401=Unauthorized - invalid credentials</li>
     *     <li>405=Method Not Allowed - only POST is honored</li>
     *     <li>408=Request Timeout - requested timed out</li>
     *     <li>500=Internal Server Error</li>
     *     <li>701=File Not Found - incorrect deploy/server uri</li>
     *     <li>702=Connection Error - failed to connect</li>
     * </ul>
     */
public static Map<String, String> getRemoteServerInfo(String serverUrl, String userId, String password) throws ConfigurationException {
    HttpURLConnection connection = null;
    try {
        connection = openConnection(serverUrl + "/getServerInfo.jsp");
        writeToConnection(connection, "IDToken1=" + URLEncoder.encode(userId, "UTF-8") + "&IDToken2=" + URLEncoder.encode(password, "UTF-8"));
        // Remove any additional /n's from the result, often seen at the beginning of the response.
        return BootstrapData.queryStringToMap(readFromConnection(connection).replace("\n", ""));
    } catch (IllegalArgumentException e) {
        debug.warning("AMSetupUtils.getRemoteServerInfo()", e);
        throw newConfigurationException("702");
    } catch (IOException e) {
        debug.warning("AMSetupUtils.getRemoteServerInfo()", e);
        if (e instanceof FileNotFoundException) {
            throw newConfigurationException("701");
        } else if (e instanceof SSLHandshakeException || e instanceof MalformedURLException || e instanceof UnknownHostException || e instanceof ConnectException) {
            throw newConfigurationException("702");
        } else {
            int status = 0;
            if (connection != null) {
                try {
                    status = connection.getResponseCode();
                } catch (Exception ignored) {
                }
            }
            if (status == 400 || status == 401 || status == 405 || status == 408) {
                throw newConfigurationException(String.valueOf(status));
            } else {
                throw new ConfiguratorException(e.getMessage());
            }
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ConnectException(java.net.ConnectException) MalformedURLException(java.net.MalformedURLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) ConfigurationException(com.sun.identity.common.configuration.ConfigurationException) ConnectException(java.net.ConnectException)

Aggregations

UnknownHostException (java.net.UnknownHostException)1736 InetAddress (java.net.InetAddress)726 IOException (java.io.IOException)446 InetSocketAddress (java.net.InetSocketAddress)150 ArrayList (java.util.ArrayList)142 SocketException (java.net.SocketException)135 Test (org.junit.Test)122 Socket (java.net.Socket)93 URL (java.net.URL)77 SocketTimeoutException (java.net.SocketTimeoutException)71 HashMap (java.util.HashMap)71 File (java.io.File)67 MalformedURLException (java.net.MalformedURLException)65 NetworkInterface (java.net.NetworkInterface)58 URI (java.net.URI)55 ConnectException (java.net.ConnectException)54 InputStream (java.io.InputStream)53 Inet4Address (java.net.Inet4Address)52 Inet6Address (java.net.Inet6Address)52 List (java.util.List)51