Example usage for java.net PasswordAuthentication PasswordAuthentication

List of usage examples for java.net PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, char[] password) 

Source Link

Document

Creates a new PasswordAuthentication object from the given user name and password.

Usage

From source file:Main.java

protected PasswordAuthentication getPasswordAuthentication() {
    String promptString = getRequestingPrompt();
    System.out.println(promptString);
    String hostname = getRequestingHost();
    System.out.println(hostname);
    InetAddress ipaddr = getRequestingSite();
    System.out.println(ipaddr);//from w w  w. j a  va  2 s.com
    int port = getRequestingPort();

    String username = "name";
    String password = "password";
    return new PasswordAuthentication(username, password.toCharArray());
}

From source file:uk.ac.ucl.cs.cmic.giftcloud.restserver.PasswordAuthenticationWrapper.java

static Optional<PasswordAuthentication> getPasswordAuthenticationFromUsernamePassword(
        final Optional<String> userName, final Optional<char[]> password) {
    if (userName.isPresent() && password.isPresent() && StringUtils.isNotBlank(userName.get())
            && ArrayUtils.isNotEmpty(password.get())) {
        return Optional.of(new PasswordAuthentication(userName.get(), password.get()));
    } else {//from   ww w . ja v a 2 s. co  m
        return Optional.empty();
    }
}

From source file:com.clustercontrol.util.EndpointManager.java

public static void setAuthenticator(String proxyUser, String proxyPass) {
    PasswordAuthentication authenticator = null;
    if (proxyUser != null && proxyUser.length() > 0) {
        authenticator = new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
    }/*w ww.ja v a  2  s .co  m*/
    getInstance().authenticator = authenticator;
}

From source file:org.restheart.test.performance.AbstractPT.java

public void prepare() {
    Authenticator.setDefault(new Authenticator() {
        @Override/* w  w  w. jav a2 s. co  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(id, pwd.toCharArray());
        }
    });

    Configuration conf;

    StringBuilder ymlSB = new StringBuilder();

    if (mongoUri != null) {
        ymlSB.append(Configuration.MONGO_URI_KEY).append(": ").append(mongoUri).append("\n");
    }

    Yaml yaml = new Yaml();

    Map<String, Object> configuration = (Map<String, Object>) yaml.load(ymlSB.toString());

    try {
        MongoDBClientSingleton.init(new Configuration(configuration, true));
    } catch (ConfigurationException ex) {
        System.out.println(ex.getMessage() + ", exiting...");
        System.exit(-1);
    }

    httpExecutor = Executor.newInstance();

    // for perf test better to disable the restheart security
    if (url != null && id != null && pwd != null) {
        String host = "127.0.0.1";
        int port = 8080;
        String scheme = "http";

        try {
            URI uri = new URI(url);

            host = uri.getHost();
            port = uri.getPort();
            scheme = uri.getScheme();
        } catch (URISyntaxException ex) {
            Logger.getLogger(LoadPutPT.class.getName()).log(Level.SEVERE, null, ex);
        }

        httpExecutor.authPreemptive(new HttpHost(host, port, scheme)).auth(new HttpHost(host), id, pwd);
    }
}

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/*from ww w. j a  v a 2s .c om*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return auth;
            }
        });
    }
}

From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public long newProcessInstance(String deploymentId, String processId, Map<String, Object> context)
        throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override//from   ww w  .ja v a  2  s .  c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        deploymentId = URLEncoder.encode(deploymentId, "UTF-8"); //$NON-NLS-1$
        processId = URLEncoder.encode(processId, "UTF-8"); //$NON-NLS-1$
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/start/%s/%s", deploymentId, processId); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        StringBuffer params = new StringBuffer();
        for (String key : context.keySet()) {
            String value = String.valueOf(context.get(key));
            value = URLEncoder.encode(value, "UTF-8"); //$NON-NLS-1$
            params.append(String.format("&%s=%s", key, value)); //$NON-NLS-1$
        }
        //remove leading '&'
        if (params.length() > 0)
            params.delete(0, 1);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        if (params.length() > 0) {
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params.toString());
            out.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            logger.info("reply=" + reply); //$NON-NLS-1$
            return Long.parseLong(reply);
        } else {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

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

/**
 * to call restful service to get license and data-source details
 * /*from  w  w w  .j a v a2 s. 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.owasp.dependencycheck.utils.URLConnectionFactory.java

/**
 * Utility method to create an HttpURLConnection. If the application is configured to use a proxy this method will retrieve
 * the proxy settings and use them when setting up the connection.
 *
 * @param url the url to connect to/*from   ww w .ja v  a 2s . c  o  m*/
 * @return an HttpURLConnection
 * @throws URLConnectionFailureException thrown if there is an exception
 */
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe")
public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
    HttpURLConnection conn = null;
    final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);

    try {
        if (proxyUrl != null && !matchNonProxy(url)) {
            final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
            final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);

            final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
            final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);

            if (username != null && password != null) {
                final Authenticator auth = new Authenticator() {
                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
                            return new PasswordAuthentication(username, password.toCharArray());
                        }
                        return super.getPasswordAuthentication();
                    }
                };
                Authenticator.setDefault(auth);
            }

            final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
        conn.setConnectTimeout(timeout);
        conn.setInstanceFollowRedirects(true);
    } catch (IOException ex) {
        if (conn != null) {
            try {
                conn.disconnect();
            } finally {
                conn = null;
            }
        }
        throw new URLConnectionFailureException("Error getting connection.", ex);
    }
    return conn;
}

From source file:org.elite.jdcbot.util.GoogleCalculation.java

public GoogleCalculation(jDCBot bot, String calc, String u) throws Exception {
    final String authUser = "pforpallav";
    final String authPassword = "buckmin$ter";
    Authenticator.setDefault(new Authenticator() {
        @Override/*from w  w  w.  ja va  2s . co m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            //logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password));
            return new PasswordAuthentication(authUser, authPassword.toCharArray());
        }
    });

    System.setProperty("http.proxyHost", "netmon.iitb.ac.in");
    System.setProperty("http.proxyPort", "80");
    System.setProperty("http.proxyUser", authUser);
    System.setProperty("http.proxyPassword", authPassword);

    String url = "http://www.google.com/ig/calculator?hl=en&q=";
    _bot = bot;
    user = u;
    calc = URLEncoder.encode(calc, "UTF-8");
    url = url + calc;
    SetURL(url);
}

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

/**
 * //from  w  ww. jav  a2  s  .  c  o m
 * 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;
}