List of usage examples for java.net PasswordAuthentication PasswordAuthentication
public PasswordAuthentication(String userName, char[] password)
From source file:sce.RESTXMLJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {//from w w w .j av a2 s . c om //JobKey key = context.getJobDetail().getKey(); JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String url = jobDataMap.getString("#url"); String binding = jobDataMap.getString("#binding"); if (url == null | binding == null) { throw new JobExecutionException("#url and #binding parameters must be not null"); } 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()); } }); } //set the url connection, to disconnect if interrupt() is requested this.urlConnection = u.openConnection(); //set the "Accept" header this.urlConnection.setRequestProperty("Accept", "application/sparql-results+xml"); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); //detect and exclude BOM //BOMInputStream bomIn = new BOMInputStream(this.urlConnection.getInputStream(), false); Document document = docBuilder.parse(this.urlConnection.getInputStream()); String result = parseXMLResponse(document.getDocumentElement(), binding, context); //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener) context.setResult(result); //if notificationEmail is defined in the job data map, then send a notification email to it if (jobDataMap.containsKey("#notificationEmail")) { sendEmail(context, jobDataMap.getString("#notificationEmail")); } //trigger the linked jobs of the finished job, depending on the job result [true, false] jobChain(context); //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result)); } catch (IOException | ParserConfigurationException | SAXException e) { e.printStackTrace(System.out); throw new JobExecutionException(e); } }
From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java
/** * Opens a connection to the provided Webhook URL. * * @param webhookUrl The Webhook URL to open a connection to. * @return The open connection to the provided Webhook URL. *//* www. jav a 2 s.c o m*/ private HttpURLConnection openConnection(String webhookUrl) { try { HttpURLConnection connection; if (StringUtils.isNotBlank(config.getProxyHost())) { LOGGER.info("Connecting via proxy"); if (StringUtils.isNotBlank(config.getProxyUsername())) { Authenticator authenticator; authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(config.getProxyUsername(), config.getProxyPassword().toCharArray())); } }; Authenticator.setDefault(authenticator); } Proxy proxy; proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort())); connection = (HttpURLConnection) new URL(webhookUrl).openConnection(proxy); } else { LOGGER.info("Connecting directly"); connection = (HttpURLConnection) new URL(webhookUrl).openConnection(); } return connection; } catch (MalformedURLException e) { throw new RuntimeException("Unable to create webhook URL: " + webhookUrl, e); } catch (IOException e) { throw new RuntimeException("Error opening connection to Slack URL: [" + e.getMessage() + "].", e); } }
From source file:org.ttrssreader.net.JavaJSONConnector.java
@Override public void init() { super.init(); if (!httpAuth) return;// w ww . j av a 2 s .c o m try { base64NameAndPw = Base64.encodeToString((httpUsername + ":" + httpPassword).getBytes("UTF-8"), Base64.NO_WRAP); } catch (UnsupportedEncodingException e) { base64NameAndPw = null; } Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(httpUsername, httpPassword.toCharArray()); } }); }
From source file:org.drools.guvnor.server.files.PackageDeploymentServletChangeSetIntegrationTest.java
@Test @RunAsClient//w w w . j a va 2 s . c o m public void applyChangeSetTwice(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "org.drools.guvnor.Guvnor/package/applyChangeSetTwice/LATEST/ChangeSet.xml"); Resource res = ResourceFactory.newUrlResource(url); KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("admin", "admin".toCharArray()); } }); KnowledgeAgent ka = KnowledgeAgentFactory.newKnowledgeAgent("test", conf); System.out.println("Applying changeset, round #1"); Thread.sleep(1000); ka.applyChangeSet(res); for (KnowledgePackage pkg : ka.getKnowledgeBase().getKnowledgePackages()) { System.out.printf(" %s (%d)%n", pkg.getName(), pkg.getRules().size()); } System.out.println("Applying changeset, round #2"); Thread.sleep(1000); ka.applyChangeSet(res); for (KnowledgePackage pkg : ka.getKnowledgeBase().getKnowledgePackages()) { System.out.printf(" %s (%d)%n", pkg.getName(), pkg.getRules().size()); } }
From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java
/** * Get the input stream from an URL.//from ww w.j a va 2s. c o m * * @param url not null * @param project could be null * @param settings not null to handle proxy settings * @param encoding the wanted encoding for the inputstream. If empty, encoding will be "ISO-8859-1". * @return the inputstream found depending the wanted encoding. * @throws IOException if any * @since 2.3 */ public static String getContent(URL url, MavenProject project, Settings settings, String encoding) throws IOException { String scheme = url.getProtocol(); if (StringUtils.isEmpty(encoding)) { encoding = "ISO-8859-1"; } if ("file".equals(scheme)) { InputStream in = null; try { URLConnection conn = url.openConnection(); in = conn.getInputStream(); return IOUtil.toString(in, encoding); } finally { IOUtil.close(in); } } Proxy proxy = settings.getActiveProxy(); if (proxy != null) { if ("http".equals(scheme) || "https".equals(scheme) || "ftp".equals(scheme)) { scheme += "."; } else { scheme = ""; } String host = proxy.getHost(); if (!StringUtils.isEmpty(host)) { Properties p = System.getProperties(); p.setProperty(scheme + "proxySet", "true"); p.setProperty(scheme + "proxyHost", host); p.setProperty(scheme + "proxyPort", String.valueOf(proxy.getPort())); if (!StringUtils.isEmpty(proxy.getNonProxyHosts())) { p.setProperty(scheme + "nonProxyHosts", proxy.getNonProxyHosts()); } final String userName = proxy.getUsername(); if (!StringUtils.isEmpty(userName)) { final String pwd = StringUtils.isEmpty(proxy.getPassword()) ? "" : proxy.getPassword(); Authenticator.setDefault(new Authenticator() { /** {@inheritDoc} */ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, pwd.toCharArray()); } }); } } } InputStream in = null; try { URLConnection conn = getURLConnection(url, project, settings); in = conn.getInputStream(); return IOUtil.toString(in, encoding); } finally { IOUtil.close(in); } }
From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java
/** * This method gets a cluster configuration and write the configuration to a * zipfile. The method returns the path of the zipfile. *//*from ww w . j ava 2 s. c o m*/ private String getClusterConfiguration(URL url) throws IOException { // This Authenticator object sets the user and password field, similar to // using the --user username:password flag with the linux curl command Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username_, password_.toCharArray()); } }); int num = rand_.nextInt(10000000); String confZipFileName = "/tmp/" + "clusterConf" + "_" + num + ".zip"; InputStream is = null; FileOutputStream fos = null; try { URLConnection conn = url.openConnection(); is = conn.getInputStream(); fos = new FileOutputStream(confZipFileName); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } return confZipFileName; }
From source file:com.uf.togathor.Togathor.java
@Override public void onCreate() { super.onCreate(); sInstance = this; mPreferences = new Preferences(this); mPreferences.clearFlagsForTutorialEachBoot(getApplicationContext().getPackageName()); gOpenFromBackground = true;// w w w. j a v a2 s. c o m mFileDir = new FileDir(this); mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); googleAPIService = new GoogleAPIService(this); messagesDataSource = new MessagesDataSource(this); eventMessagesDataSource = new EventMessagesDataSource(this); contactsDataSource = new ContactsDataSource(this); startEventService(); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("s3lab", "S3LAB!!".toCharArray()); } }); // Create typefaces mTfMyriadPro = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf"); mTfMyriadProBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf"); setTransportBasedOnScreenDensity(42); // Example interpolator; could use linear or accelerate interpolator // instead final AccelerateDecelerateInterpolator accDecInterpolator = new AccelerateDecelerateInterpolator(); final LinearInterpolator linearInterpolator = new LinearInterpolator(); final int slidingDuration = getResources().getInteger(R.integer.sliding_duration); // Set up animations mSlideInLeft = new TranslateAnimation(-mTransport, 0, 0, 0); mSlideInLeft.setDuration(slidingDuration); // mSlideInLeft.setFillAfter(true); // hmm not sure mSlideInLeft.setFillEnabled(false); mSlideInLeft.setInterpolator(linearInterpolator); mSlideOutRight = new TranslateAnimation(0, mTransport, 0, 0); mSlideOutRight.setDuration(slidingDuration); mSlideOutRight.setFillAfter(true); mSlideOutRight.setFillEnabled(true); mSlideOutRight.setInterpolator(linearInterpolator); mSlideOutLeft = new TranslateAnimation(0, -mTransport, 0, 0); mSlideOutLeft.setDuration(slidingDuration); mSlideOutLeft.setInterpolator(linearInterpolator); mSlideInRight = new TranslateAnimation(mTransport, 0, 0, 0); mSlideInRight.setDuration(slidingDuration); mSlideInRight.setFillAfter(true); mSlideInRight.setFillEnabled(true); mSlideInRight.setInterpolator(linearInterpolator); mSlideFromTop.setFillAfter(true); mSlideFromTop.setFillEnabled(true); mSlideFromTop.setDuration(this.getResources().getInteger(android.R.integer.config_mediumAnimTime)); mSlideFromTop.setInterpolator(linearInterpolator); mSlideOutTop.setDuration(this.getResources().getInteger(android.R.integer.config_mediumAnimTime)); mSlideOutTop.setInterpolator(linearInterpolator); String strUUID = UUID.randomUUID().toString(); Logger.debug("uuid", strUUID); mBaseUrl = mPreferences.getUserServerURL(); }
From source file:sce.RESTJobStateful.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {//from w w w . j ava 2 s . co m JobKey key = context.getJobDetail().getKey(); JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String url = jobDataMap.getString("#url"); 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()); } }); } //set the url connection, to disconnect if interrupt() is requested this.urlConnection = u.openConnection(); String result = getUrlContents(this.urlConnection); //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener) context.setResult(result); //if notificationEmail is defined in the job data map, then send a notification email to it if (jobDataMap.containsKey("#notificationEmail")) { sendEmail(context, jobDataMap.getString("#notificationEmail")); } //trigger the linked jobs of the finished job, depending on the job result [true, false] jobChain(context); //Mail.sendMail("prova", "disdsit@gmail.com", "prova di email", "", ""); System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result)); } catch (MalformedURLException e) { throw new JobExecutionException(e); } catch (IOException e) { throw new JobExecutionException(e); } }
From source file:org.talend.core.nexus.NexusServerUtils.java
private static void search(String nexusUrl, final String userName, final String password, String repositoryId, String groupIdToSearch, String artifactId, String versionToSearch, int searchFrom, int searchCount, List<MavenArtifact> artifacts) throws Exception { HttpURLConnection urlConnection = null; int totalCount = 0; final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator(); if (userName != null && !"".equals(userName)) { Authenticator.setDefault(new Authenticator() { @Override/*from w ww . jav a 2 s . co m*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } try { String service = NexusConstants.SERVICES_SEARCH + getSearchQuery(repositoryId, groupIdToSearch, artifactId, versionToSearch, searchFrom, searchCount); urlConnection = getHttpURLConnection(nexusUrl, service, userName, password); SAXReader saxReader = new SAXReader(); InputStream inputStream = urlConnection.getInputStream(); Document document = saxReader.read(inputStream); // test // writeDocument(document, new File("D:/search.txt")); Node countNode = document.selectSingleNode("/searchNGResponse/totalCount"); if (countNode != null) { try { totalCount = Integer.parseInt(countNode.getText()); } catch (NumberFormatException e) { totalCount = 0; } } List<Node> list = document.selectNodes("/searchNGResponse/data/artifact");//$NON-NLS-1$ for (Node arNode : list) { MavenArtifact artifact = new MavenArtifact(); artifacts.add(artifact); artifact.setGroupId(arNode.selectSingleNode("groupId").getText());//$NON-NLS-1$ artifact.setArtifactId(arNode.selectSingleNode("artifactId").getText());//$NON-NLS-1$ artifact.setVersion(arNode.selectSingleNode("version").getText());//$NON-NLS-1$ Node descNode = arNode.selectSingleNode("description");//$NON-NLS-1$ if (descNode != null) { artifact.setDescription(descNode.getText()); } Node urlNode = arNode.selectSingleNode("url");//$NON-NLS-1$ if (urlNode != null) { artifact.setUrl(urlNode.getText()); } Node licenseNode = arNode.selectSingleNode("license");//$NON-NLS-1$ if (licenseNode != null) { artifact.setLicense(licenseNode.getText()); } Node licenseUrlNode = arNode.selectSingleNode("licenseUrl");//$NON-NLS-1$ if (licenseUrlNode != null) { artifact.setLicenseUrl(licenseUrlNode.getText()); } List<Node> artLinks = arNode.selectNodes("artifactHits/artifactHit/artifactLinks/artifactLink");//$NON-NLS-1$ for (Node link : artLinks) { Node extensionElement = link.selectSingleNode("extension");//$NON-NLS-1$ String extension = null; String classifier = null; if (extensionElement != null) { if ("pom".equals(extensionElement.getText())) {//$NON-NLS-1$ continue; } extension = extensionElement.getText(); } Node classifierElement = link.selectSingleNode("classifier");//$NON-NLS-1$ if (classifierElement != null) { classifier = classifierElement.getText(); } artifact.setType(extension); artifact.setClassifier(classifier); } } int searchDone = searchFrom + searchCount; int count = MAX_SEARCH_COUNT; if (searchDone < totalCount) { if (totalCount - searchDone < MAX_SEARCH_COUNT) { count = totalCount - searchDone; } search(nexusUrl, userName, password, repositoryId, groupIdToSearch, artifactId, versionToSearch, searchDone + 1, count, artifacts); } } finally { Authenticator.setDefault(defaultAuthenticator); if (null != urlConnection) { urlConnection.disconnect(); } } }
From source file:sce.RESTAppMetricJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { Connection conn = null;/* w ww . j a v a 2s . c o m*/ try { String url1 = prop.getProperty("kb_url"); //required parameters #url JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query if (callUrl == null) { throw new JobExecutionException("#url parameter must be not null"); } String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url if (timeout == null) { timeout = "5000"; } //first SPARQL query to retrieve application related metrics and business configurations String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8"); URL u = new URL(url); final String usernamePassword = u.getUserInfo(); if (usernamePassword != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(usernamePassword.split(":")[0], usernamePassword.split(":")[1].toCharArray()); } }); } this.urlConnection = u.openConnection(); this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json"); HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(), HashMap.class); HashMap<String, Object> r = (HashMap<String, Object>) res.get("results"); ArrayList<Object> list = (ArrayList<Object>) r.get("bindings"); ArrayList<String[]> lst = new ArrayList<>(); for (Object obj : list) { HashMap<String, Object> o = (HashMap<String, Object>) obj; String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); lst.add(new String[] { mn, bc }); } //second SPARQL query to retrieve alerts for SLA url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8"); u = new URL(url); //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false); //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream); //out.write(getAlertsForSLA(lst, slaTimestamp)); //out.close(); this.urlConnection = u.openConnection(); this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json"); //format the result HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(), HashMap.class); HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results"); ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings"); String result = ""; //MYSQL CONNECTION conn = Main.getConnection(); // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close() int counter = 0; //SET timestamp FOR MYSQL ROW Date dt = new java.util.Date(); SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String timestamp = sdf.format(dt); // JSON to be sent to the SM JSONArray jsonArray = new JSONArray(); for (Object obj : list1) { //JSON to insert into database //JSONArray jsonArray = new JSONArray(); HashMap<String, Object> o = (HashMap<String, Object>) obj; String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration // add these metric value to the json array JSONObject object = new JSONObject(); object.put("business_configuration", bc); object.put("metric", sm); object.put("metric_name", mn); object.put("metric_unit", mu); object.put("value", v); object.put("metric_timestamp", mt); jsonArray.add(object); //INSERT THE DATA INTO DATABASE PreparedStatement preparedStatement = conn.prepareStatement( "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?"); preparedStatement.setString(1, timestamp); // date preparedStatement.setString(2, sm); // metric preparedStatement.setString(3, mn); // metric_name preparedStatement.setString(4, mu); // metric_unit preparedStatement.setString(5, v); // value preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00) preparedStatement.setString(7, bc); // business_configuration preparedStatement.setString(8, timestamp); // date preparedStatement.executeUpdate(); preparedStatement.close(); result += "\nService Metric: " + sm + "\n"; result += "\nMetric Name: " + mn + "\n"; result += "\nMetric Unit: " + mu + "\n"; result += "Timestamp: " + mt + "\n"; result += "Business Configuration: " + bc + "\n"; result += "Value" + (counter + 1) + ": " + v + "\n"; result += "Call Url: " + callUrl + "\n"; counter++; } // send the JSON to the CM URL tmp_u = new URL(callUrl); final String usr_pwd = tmp_u.getUserInfo(); String usr = null; String pwd = null; if (usr_pwd != null) { usr = usr_pwd.split(":")[0]; pwd = usr_pwd.split(":")[1]; } sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout)); //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener) context.setResult(result); if (jobDataMap.containsKey("#notificationEmail")) { sendEmail(context, jobDataMap.getString("#notificationEmail")); } jobChain(context); } catch (MalformedURLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (IOException | SQLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (!conn.isClosed()) { conn.close(); } } catch (SQLException ex) { Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex); } } }