Example usage for java.net Authenticator Authenticator

List of usage examples for java.net Authenticator Authenticator

Introduction

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

Prototype

Authenticator

Source Link

Usage

From source file:org.pentaho.supportutility.rest.client.RestFulClient.java

/**
 * to call restful service to get license and data-source details
 * /* w w  w  .  jav a2s .co m*/
 * @param server
 * @param required
 * @param prop
 * @param webXml
 * @return
 */
public static String restFulService(String server, String required, final Properties prop, String webXml) {

    String outPut = null;
    String qualifiedUrl = null;
    // based on server get restful url
    if (server.equalsIgnoreCase(RestFulURL.BI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_BISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.DI_SERVER)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    } else if (server.equalsIgnoreCase(RestFulURL.SPOON_IDE)) {

        qualifiedUrl = prop.getProperty(RestFulURL.FULLY_QUALIFIED_DISERVER_URL);
    }
    URL url = null;

    try {
        if (required.equalsIgnoreCase(RestFulURL.LICENSE)) {

            url = getLicenseUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.ANALYSIS)) {

            url = getAnalysisUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.METADATA)) {

            url = getMateDataUrl(qualifiedUrl);
        } else if (required.equalsIgnoreCase(RestFulURL.DSW)) {

            url = getDSW(qualifiedUrl);
        }

        // authenticating the restful service
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prop.getProperty(RestFulURL.USER_NAME),
                        prop.getProperty(RestFulURL.USER_PASSWORD).toCharArray());
            }

        });

        String basicAuth = RestFulURL.BASIC
                + new String(Base64.encodeBase64((prop.getProperty(RestFulURL.USER_NAME) + RestFulURL.COLON
                        + prop.getProperty(RestFulURL.USER_PASSWORD)).getBytes()));

        if (url != null) {
            // calling restful service
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection conn = (HttpURLConnection) urlConnection;
            urlConnection.setRequestProperty(RestFulURL.AUTHOR, basicAuth);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                outPut = br.readLine();
            }

            conn.disconnect();
        }

    } catch (MalformedURLException e) {
        e.getMessage();
    } catch (IOException e) {
        e.getMessage();
    }

    return outPut;

}

From source file:org.openintents.lib.DeliciousApiHelper.java

public DeliciousApiHelper(String api, String user, String passwd) {
    this.mAPI = api;
    this.mUser = user;
    this.mPasswd = passwd;

    //init the authentication
    Authenticator.setDefault(new Authenticator() {
        @Override/*from  ww w.  ja va 2 s .c  om*/
        protected PasswordAuthentication getPasswordAuthentication() {
            System.out.printf("url=%s, host=%s, ip=%s, port=%s%n", getRequestingURL(), getRequestingHost(),
                    getRequestingSite(), getRequestingPort());

            return new PasswordAuthentication(DeliciousApiHelper.this.mUser,
                    DeliciousApiHelper.this.mPasswd.toCharArray());
        }
    });

}

From source file:org.talend.core.nexus.NexusServerUtils.java

/**
 * //from   w w  w  . j ava2  s  .  com
 * DOC check if the repository exist or not
 * 
 * @param nexusUrl
 * @param repositoryId
 * @param userName
 * @param password
 * @return
 */
public static boolean checkConnectionStatus(String nexusUrl, String repositoryId, final String userName,
        final String password) {
    if (StringUtils.isEmpty(nexusUrl)) {
        return false;
    }
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    int status = -1;
    try {
        if (nexusUrl == null || "".equals(nexusUrl) || repositoryId == null || "".equals(repositoryId)) {
            return false;
        }
        String newUrl = nexusUrl;
        if (newUrl.endsWith(NexusConstants.SLASH)) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        String urlToCheck = newUrl + NexusConstants.CONTENT_REPOSITORIES + repositoryId;

        URL url = new URL(urlToCheck);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            String userDir = Platform.getInstallLocation().getURL().getPath();
            final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
            HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
            httpsConnection.setSSLSocketFactory(socketFactory);
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

            });
        }
        IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE);
        int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000);

        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        status = urlConnection.getResponseCode();
        if (status == CONNECTION_OK) {
            return true;
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
    }
    return false;
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SocksSocketFactory.java

SocksSocketFactory(String socksHost, int socksPort, final String user, final String pass) {
    this.socksHost = socksHost;
    this.socksPort = socksPort;

    if (StringUtils.hasText(user)) {
        final PasswordAuthentication auth = new PasswordAuthentication(user, pass.toCharArray());

        Authenticator.setDefault(new Authenticator() {
            @Override/*w w  w  . j  av a2 s.co  m*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return auth;
            }
        });
    }
}

From source file:org.phenotips.internal.ProxyAuthenticator.java

@Override
public void onEvent(Event event, Object source, Object data) {
    final String proxyUser = System.getProperty("http.proxyUser");
    final String proxyPassword = System.getProperty("http.proxyPassword");
    if (StringUtils.isNoneBlank(proxyUser, proxyPassword)) {
        Authenticator.setDefault(new Authenticator() {
            @Override/*from w w w  .j av a2  s .c  o m*/
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
}

From source file:com.pras.conn._HttpConHandler.java

private Proxy getProxy() {
    /**/*from   w w  w  . j  av a  2  s .  c  o m*/
     * Connect through a Proxy
     */
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray());
        }
    });
    return new Proxy(Type.HTTP, new InetSocketAddress(PROXY_URL, PROXY_PORT));
    //      return Proxy.NO_PROXY;
}

From source file:org.talend.commons.utils.network.NetworkUtil.java

public static void loadAuthenticator() {
    // get parameter from System.properties.
    if (Boolean.getBoolean("http.proxySet")) {//$NON-NLS-1$
        // authentification for the url by using username and password
        Authenticator.setDefault(new Authenticator() {

            @Override/*from w ww.j  a va 2s. c o m*/
            protected PasswordAuthentication getPasswordAuthentication() {
                String httpProxyUser = System.getProperty("http.proxyUser"); //$NON-NLS-1$
                String httpProxyPassword = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
                String httpsProxyUser = System.getProperty("https.proxyUser"); //$NON-NLS-1$
                String httpsProxyPassword = System.getProperty("https.proxyPassword"); //$NON-NLS-1$
                String proxyUser = null;
                char[] proxyPassword = new char[0];
                if (StringUtils.isNotEmpty(httpProxyUser)) {
                    proxyUser = httpProxyUser;
                    if (StringUtils.isNotEmpty(httpProxyPassword)) {
                        proxyPassword = httpProxyPassword.toCharArray();
                    }
                } else if (StringUtils.isNotEmpty(httpsProxyUser)) {
                    proxyUser = httpsProxyUser;
                    if (StringUtils.isNotEmpty(httpsProxyPassword)) {
                        proxyPassword = httpsProxyPassword.toCharArray();
                    }
                }
                return new PasswordAuthentication(proxyUser, proxyPassword);
            }

        });
    } else {
        Authenticator.setDefault(null);
    }
}

From source file:de.stadtrallye.rallyesoft.net.AuthProvider.java

public Authenticator getAuthenticator() {
    return new Authenticator() {
        @Override/*  w  w  w  .j  a  v a2 s . c  o  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            if (realm.equals(Authentication.USER_AUTH)) {
                Log.i(THIS, "Using Fallback-UserAuthentication");
                return new PasswordAuthentication(userAuth.getHttpUser(groupID),
                        userAuth.password.toCharArray());
            } else if (realm.equals(Authentication.GROUP_AUTH)) {
                Log.i(THIS, "Using Fallback-GroupAuthentication");
                return new PasswordAuthentication(String.valueOf(groupID), groupPassword.toCharArray());
            } else {
                return null;
            }
        }
    };
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method sends a get request to CM using the given URL. The return value
 * of that request is returned in the method in string form.
 *//*  w w  w  .j av  a  2s . c om*/
public String clusterGetRequest(URL url) throws IOException {
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username_, password_.toCharArray());
        }
    });
    StringBuilder ret = new StringBuilder();
    BufferedReader br = null;
    try {
        URLConnection cc = url.openConnection();
        br = new BufferedReader(new InputStreamReader(cc.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            ret.append(line);
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }
    return ret.toString();
}

From source file:de.rallye.test.GroupsTest.java

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override//from ww  w  .ja  va 2s. c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            assertEquals("Should be right Realm", "RallyeNewUser", realm);
            return new PasswordAuthentication(String.valueOf(1), "test".toCharArray());
        }
    });
    URL url = new URL("http://127.0.0.1:10111/groups/1");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    //      conn.setFixedLengthStreamingMode(post.length);
    conn.getOutputStream().write(MockDataAdapter.validLogin.getBytes());

    int code = conn.getResponseCode();

    Authenticator.setDefault(null);

    try {
        assertEquals("Code should be 200", 200, code);
    } catch (AssertionError e) {
        System.err.println("This is the content:");
        List<String> contents = IOUtils.readLines((InputStream) conn.getContent());
        for (String line : contents)
            System.err.println(line);
        throw e;
    }

}