List of usage examples for java.net Authenticator Authenticator
Authenticator
From source file:cc.arduino.net.CustomProxySelector.java
private void setAuthenticator(String username, String password) { if (username == null || username.isEmpty()) { return;//from w w w. j a v a 2 s . c o m } String actualPassword; if (password == null) { actualPassword = ""; } else { actualPassword = password; } Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, actualPassword.toCharArray()); } }); }
From source file:sce.ElasticJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {/* w w w.j a va 2 s . co m*/ // build the list of queries ArrayList<String> queries = new ArrayList<>(); JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String url = jobDataMap.getString("#url"); String elasticJob = jobDataMap.getString("#elasticJobConstraints"); int counter = 0; String expression = ""; String j_tmp = ""; JSONParser parser = new JSONParser(); JSONObject jsonobject = (JSONObject) parser.parse(elasticJob); Iterator<?> keys = jsonobject.keySet().iterator(); while (keys.hasNext()) { String i = (String) keys.next(); JSONObject jsonobject2 = (JSONObject) jsonobject.get(i); Iterator<?> keys2 = jsonobject2.keySet().iterator(); while (keys2.hasNext()) { String j = (String) keys2.next(); JSONObject jsonobject3 = (JSONObject) jsonobject2.get(j); String configuration = ""; if (jsonobject3.get("slaconfiguration") != null) { configuration = (String) jsonobject3.get("slaconfiguration"); } else if (jsonobject3.get("bcconfiguration") != null) { configuration = (String) jsonobject3.get("bcconfiguration"); } else if (jsonobject3.get("vmconfiguration") != null) { configuration = (String) jsonobject3.get("vmconfiguration"); } else if (jsonobject3.get("anyconfiguration") != null) { configuration = (String) jsonobject3.get("anyconfiguration"); } // add the query to the queries list queries.add(getQuery((String) jsonobject3.get("metric"), (String) jsonobject3.get("cfg"), configuration, (String) jsonobject3.get("relation"), String.valueOf(jsonobject3.get("threshold")), String.valueOf(jsonobject3.get("time")), (String) jsonobject3.get("timeselect"))); String op = jsonobject3.get("match") != null ? (String) jsonobject3.get("match") : ""; switch (op) { case "": break; case "any": op = "OR("; break; case "all": op = "AND("; break; } String closed_parenthesis = " "; int num_closed_parenthesis = !j_tmp.equals("") ? Integer.parseInt(j_tmp) - Integer.parseInt(j) : 0; for (int parenthesis = 0; parenthesis < num_closed_parenthesis; parenthesis++) { closed_parenthesis += " )"; } expression += op + " " + counter + closed_parenthesis; j_tmp = j; counter++; } } ExpressionTree calc = new ExpressionTree(new Scanner(expression), queries); if (calc.evaluate()) { URL u = new URL(url); //get user credentials from URL, if present final String usernamePassword = u.getUserInfo(); //set the basic authentication credentials for the connection if (usernamePassword != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(usernamePassword.split(":")[0], usernamePassword.split(":")[1].toCharArray()); } }); } //call the callUrl URLConnection connection = u.openConnection(); getUrlContents(connection); } } catch (Exception e) { e.printStackTrace(); throw new JobExecutionException(e); } }
From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java
private HttpURLConnection createConnection(final String location) throws IOException { URL url = new URL(location); HttpURLConnection conn;/*ww w . j a va2 s .c o m*/ if (proxyHost != null && proxyPort != null) { if (proxyUser != null && proxyPassword != null) { Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }; Authenticator.setDefault(authenticator); } Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } return conn; }
From source file:org.sonar.plugins.github.GitHubPluginConfiguration.java
public Proxy getHttpProxy() { try {/* ww w. j a v a 2 s . co m*/ if (system2.property(HTTP_PROXY_HOSTNAME) != null && system2.property(HTTPS_PROXY_HOSTNAME) == null) { System.setProperty(HTTPS_PROXY_HOSTNAME, system2.property(HTTP_PROXY_HOSTNAME)); System.setProperty(HTTPS_PROXY_PORT, system2.property(HTTP_PROXY_PORT)); } String proxyUser = system2.property(HTTP_PROXY_USER); String proxyPass = system2.property(HTTP_PROXY_PASS); if (proxyUser != null && proxyPass != null) { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPass.toCharArray()); } }); } Proxy selectedProxy = ProxySelector.getDefault().select(new URI(endpoint())).get(0); if (selectedProxy.type() == Proxy.Type.DIRECT) { LOG.debug("There was no suitable proxy found to connect to GitHub - direct connection is used "); } LOG.info("A proxy has been configured - {}", selectedProxy.toString()); return selectedProxy; } catch (URISyntaxException e) { throw new IllegalArgumentException( "Unable to perform GitHub WS operation - endpoint in wrong format: " + endpoint(), e); } }
From source file:com.redhat.rcm.version.config.DefaultSessionConfigurator.java
private void loadSettings(final VersionManagerSession session) { MavenExecutionRequest executionRequest = session.getExecutionRequest(); if (executionRequest == null) { executionRequest = new DefaultMavenExecutionRequest(); }/*w ww . jav a2 s . c om*/ File settingsXml; try { settingsXml = getFile(session.getSettingsXml(), session.getDownloads()); } catch (final VManException e) { session.addError(e); return; } final DefaultSettingsBuildingRequest req = new DefaultSettingsBuildingRequest(); req.setUserSettingsFile(settingsXml); req.setSystemProperties(System.getProperties()); try { final SettingsBuildingResult result = settingsBuilder.build(req); final Settings settings = result.getEffectiveSettings(); final String proxyHost = System.getProperty("http.proxyHost"); final String proxyPort = System.getProperty("http.proxyPort", "8080"); final String nonProxyHosts = System.getProperty("http.nonProxyHosts", "localhost"); final String proxyUser = System.getProperty("http.proxyUser"); final String proxyPassword = System.getProperty("http.proxyPassword"); if (proxyHost != null) { final Proxy proxy = new Proxy(); proxy.setActive(true); proxy.setHost(proxyHost); proxy.setId("cli"); proxy.setNonProxyHosts(nonProxyHosts); proxy.setPort(Integer.parseInt(proxyPort)); if (proxyUser != null && proxyPassword != null) { proxy.setUsername(proxyUser); proxy.setPassword(proxyPassword); Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } settings.setProxies(Collections.singletonList(proxy)); } executionRequest = requestPopulator.populateFromSettings(executionRequest, settings); session.setExecutionRequest(executionRequest); } catch (final SettingsBuildingException e) { session.addError(new VManException("Failed to build settings from: %s. Reason: %s", e, settingsXml, e.getMessage())); } catch (final MavenExecutionRequestPopulationException e) { session.addError(new VManException("Failed to initialize system using settings from: %s. Reason: %s", e, settingsXml, e.getMessage())); } }
From source file:hudson.ProxyConfiguration.java
/** * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly. *///w ww . ja v a 2 s . c om public static URLConnection open(URL url) throws IOException { Jenkins h = Jenkins.getInstance(); // this code might run on slaves ProxyConfiguration p = h != null ? h.proxy : null; if (p == null) return url.openConnection(); URLConnection con = url.openConnection(p.createProxy(url.getHost())); if (p.getUserName() != null) { // Add an authenticator which provides the credentials for proxy authentication Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() != RequestorType.PROXY) return null; ProxyConfiguration p = Jenkins.getInstance().proxy; return new PasswordAuthentication(p.getUserName(), p.getPassword().toCharArray()); } }); } for (URLConnectionDecorator d : URLConnectionDecorator.all()) d.decorate(con); return con; }
From source file:net.myrrix.client.ClientRecommender.java
/** * Instantiates a new recommender client with the given configuration * * @param config configuration to use with this client * @throws IOException if the HTTP client encounters an error during configuration *///from w w w . j a v a2 s .co m public ClientRecommender(MyrrixClientConfiguration config) throws IOException { Preconditions.checkNotNull(config); this.config = config; final String userName = config.getUserName(); final String password = config.getPassword(); needAuthentication = userName != null && password != null; if (needAuthentication) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } if (config.getKeystoreFile() != null) { log.warn("A keystore file has been specified. " + "This should only be done to accept self-signed certificates in development."); HttpsURLConnection.setDefaultSSLSocketFactory(buildSSLSocketFactory()); } closeConnection = Boolean.valueOf(System.getProperty(CONNECTION_CLOSE_KEY)); ignoreHTTPSHost = Boolean.valueOf(System.getProperty(IGNORE_HOSTNAME_KEY)); partitions = config.getPartitions(); }
From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java
private Document getXMLStatusFile(Board board) { final Board b = board; //get the xml file from the socket connection DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try {// w w w. j a va2 s . c o m dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { LOG.error(ex.getMessage()); } Document doc = null; String statusFileURL = null; try { if (board.getAuthentication().equalsIgnoreCase("true")) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(b.getUsername(), b.getPassword().toCharArray()); } }); statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort()) + b.getPathAuthentication() + "/" + GET_STATUS_URL; } else { statusFileURL = "http://" + board.getIpAddress() + ":" + Integer.toString(board.getPort()) + "/" + GET_STATUS_URL; } LOG.info("Ipx800 gets relay status from file {0}", statusFileURL); doc = dBuilder.parse(new URL(statusFileURL).openStream()); doc.getDocumentElement().normalize(); } catch (ConnectException connEx) { LOG.error(Freedomotic.getStackTraceInfo(connEx)); //disconnect(); this.stop(); this.setDescription("Connection timed out, no reply from the board at " + statusFileURL); } catch (SAXException ex) { //this.stop(); LOG.error(Freedomotic.getStackTraceInfo(ex)); } catch (Exception ex) { //this.stop(); setDescription("Unable to connect to " + statusFileURL); LOG.error(Freedomotic.getStackTraceInfo(ex)); } return doc; }
From source file:org.kawanfw.commons.client.http.HttpTransferOne.java
/** * Sets the proxy credentials//from ww w. j a v a2 s . c o m * */ private void setProxyCredentials() { if (proxy == null) { try { displayErrroMessageIfNoProxySet(); } catch (Exception e) { e.printStackTrace(); } return; } // Sets the credential for authentication if (passwordAuthentication != null) { final String proxyAuthUsername = passwordAuthentication.getUserName(); final char[] proxyPassword = passwordAuthentication.getPassword(); Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyAuthUsername, proxyPassword); } }; Authenticator.setDefault(authenticator); } }
From source file:hudson.remoting.Launcher.java
public void run() throws Exception { if (auth != null) { final int idx = auth.indexOf(':'); if (idx < 0) throw new CmdLineException(null, "No ':' in the -auth option"); Authenticator.setDefault(new Authenticator() { @Override// w w w.j a va 2 s .c om public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(auth.substring(0, idx), auth.substring(idx + 1).toCharArray()); } }); } if (connectionTarget != null) { runAsTcpClient(); System.exit(0); } else if (slaveJnlpURL != null) { List<String> jnlpArgs = parseJnlpArguments(); try { hudson.remoting.jnlp.Main._main(jnlpArgs.toArray(new String[jnlpArgs.size()])); } catch (CmdLineException e) { System.err.println("JNLP file " + slaveJnlpURL + " has invalid arguments: " + jnlpArgs); System.err.println("Most likely a configuration error in the master"); System.err.println(e.getMessage()); System.exit(1); } } else if (tcpPortFile != null) { runAsTcpServer(); System.exit(0); } else { runWithStdinStdout(); System.exit(0); } }