List of usage examples for java.net PasswordAuthentication PasswordAuthentication
public PasswordAuthentication(String userName, char[] password)
From source file:edu.indiana.lib.twinpeaks.net.HttpAuthenticator.java
/** * Override the default implementation to provide the credentials required * for our network authentication//from w ww . j av a2 s . c o m */ protected synchronized PasswordAuthentication getPasswordAuthentication() { Credentials credential; int attempts; _log.debug("Authorization requested for \"" + getRequestingPrompt() + "\", scheme: \"" + getRequestingScheme() + "\", site: \"" + getRequestingSite() + "\""); credential = (Credentials) credentialMap.get(getRequestingPrompt()); if (credential == null) { _log.warn("No credentials configured"); return null; } /* * If the login has been rejected once, quit now. This avoids a * "redirect loop" with the server. Reset the counter every few * attempts to allow an an occasional authorization "retry". */ attempts = credential.getAuthorizationAttempts() + 1; credential.setAuthorizationAttempts(attempts); if (attempts > 1) { if ((attempts % 3) == 0) { credential.setAuthorizationAttempts(0); } _log.warn("Authorization refused"); return null; } _log.warn("Returning credentials for authorization"); return new PasswordAuthentication(credential.getUsername(), credential.getPassword()); }
From source file:org.kawanfw.test.parms.ProxyLoader.java
public Proxy getProxy() throws IOException, URISyntaxException { if (FrameworkSystemUtil.isAndroid()) { return null; }//from ww w . j a va 2s . c o m System.setProperty("java.net.useSystemProxies", "true"); List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com/")); if (proxies != null && proxies.size() >= 1) { System.out.println("Loading proxy file info..."); if (proxies.get(0).type().equals(Proxy.Type.DIRECT)) { return null; } File file = new File(NEOTUNNEL_TXT); if (file.exists()) { String proxyValues = FileUtils.readFileToString(file); String username = StringUtils.substringBefore(proxyValues, " "); String password = StringUtils.substringAfter(proxyValues, " "); username = username.trim(); password = password.trim(); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)); passwordAuthentication = new PasswordAuthentication(username, password.toCharArray()); System.out.println("USING PROXY WITH AUTHENTICATION: " + proxy + " / " + username + " " + password); } else { throw new FileNotFoundException("proxy values not found. No file " + file); } } return proxy; }
From source file:org.kawanfw.file.test.parms.ProxyLoader.java
public Proxy getProxy() throws IOException, URISyntaxException { if (FrameworkSystemUtil.isAndroid()) { return null; }/* ww w. j av a 2 s . co m*/ System.setProperty("java.net.useSystemProxies", "true"); List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com/")); if (proxies != null && proxies.size() >= 1) { System.out.println("Proxy in use: " + proxies.get(0)); if (proxies.get(0).type().equals(Proxy.Type.DIRECT)) { return null; } System.out.println("Loading proxy file info..."); // System.setProperty("java.net.useSystemProxies", "false"); File file = new File(NEOTUNNEL_TXT); if (file.exists()) { String proxyValues = FileUtils.readFileToString(file); String username = StringUtils.substringBefore(proxyValues, " "); String password = StringUtils.substringAfter(proxyValues, " "); // proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( // "127.0.0.1", 8080)); proxy = proxies.get(0); passwordAuthentication = new PasswordAuthentication(username, password.toCharArray()); System.out.println("USING PROXY WITH AUTHENTICATION: " + proxy + " / " + username + "-" + password); } else { throw new FileNotFoundException("proxy values not found. No file " + file); } } return proxy; }
From source file:sce.RESTJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {/*w w w . java 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.restheart.test.performance.LoadGetPT.java
/** * */// w w w .j av a 2 s. c om public void prepare() { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(id, pwd.toCharArray()); } }); try { MongoDBClientSingleton.init(FileUtils.getConfiguration(CONF_FILE, false)); } catch (ConfigurationException ex) { System.out.println(ex.getMessage() + ", exiting..."); System.exit(-1); } httpExecutor = Executor.newInstance(); // for perf test we disable the restheart security //.authPreemptive(new HttpHost("127.0.0.1", 8080, "http")).auth(new HttpHost("127.0.0.1"), id, pwd); }
From source file:gov.nasa.ensemble.core.rcp.EnsembleApplication.java
@Override public Object start(IApplicationContext context) throws Exception { //// ww w . ja v a 2 s . c o m // Comment out check until the missing // if (!checkWorkspaceLock(new Shell(PlatformUI.createDisplay(), SWT.ON_TOP))) { // Platform.endSplash(); // return IApplication.EXIT_OK; // } String productName = "Ensemble"; if (Platform.getProduct() != null) productName = Platform.getProduct().getName(); Display.setAppName(productName); Authenticator login = AuthenticationUtil.getAuthenticator(); boolean isAuthenticated = false; if (login != null) { // may need these credentials later credentials = login.getCredentials(); isAuthenticated = login.isAuthenticated(); } else { // Setup the authenticator that gets us through the password check on the website java.net.Authenticator.setDefault(new java.net.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { Properties properties = CommonPlugin.getDefault().getEnsembleProperties(); String user = properties.getProperty(APACHE_SERVER_USER_PROPERTY, ""); String pass = properties.getProperty(APACHE_SERVER_PASS_PROPERTY, ""); return new PasswordAuthentication(user, pass.toCharArray()); } }); isAuthenticated = true; } Display display = null; String sleakEnabled = EnsembleProperties.getProperty("sleak.enabled"); if (sleakEnabled != null && Boolean.valueOf(sleakEnabled)) { DeviceData data = new DeviceData(); data.tracking = true; display = new Display(data); Sleak sleak = new Sleak(); sleak.open(); } else { display = Display.getDefault(); } PlatformUI.createDisplay(); try { if (isAuthenticated) { WorkbenchAdvisor workbenchAdvisor; try { workbenchAdvisor = MissionExtender.construct(EnsembleWorkbenchAdvisor.class); } catch (ConstructionException e) { trace.warn("couldn't instantiate mission-specific EnsembleWorkbenchAdvisor"); workbenchAdvisor = new EnsembleWorkbenchAdvisor() { @Override public String getInitialWindowPerspectiveId() { return null; } }; } DynamicExtensionUtils.removeIgnoredExtensions(); int returnCode = PlatformUI.createAndRunWorkbench(display, workbenchAdvisor); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } return IApplication.EXIT_OK; } // authentication failed context.applicationRunning(); return IApplication.EXIT_OK; } finally { display.dispose(); } }
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/* w w w. j a v a2 s .c om*/ 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:org.eclipse.kura.core.deployment.download.impl.HttpDownloadCountingOutputStream.java
@Override public void startWork() throws KuraException { this.executor = Executors.newSingleThreadExecutor(); this.future = this.executor.submit(new Callable<Void>() { @Override//from w w w . jav a 2s . com public Void call() throws Exception { URL localUrl = null; boolean shouldAuthenticate = false; try { shouldAuthenticate = HttpDownloadCountingOutputStream.this.options.getUsername() != null && HttpDownloadCountingOutputStream.this.options.getPassword() != null && !(HttpDownloadCountingOutputStream.this.options.getUsername().trim().isEmpty() && !HttpDownloadCountingOutputStream.this.options.getPassword().trim() .isEmpty()); if (shouldAuthenticate) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( HttpDownloadCountingOutputStream.this.options.getUsername(), HttpDownloadCountingOutputStream.this.options.getPassword().toCharArray()); } }); } localUrl = new URL(HttpDownloadCountingOutputStream.this.m_downloadURL); URLConnection urlConnection = localUrl.openConnection(); int connectTimeout = getConnectTimeout(); int readTimeout = getPropReadTimeout(); urlConnection.setConnectTimeout(connectTimeout); urlConnection.setReadTimeout(readTimeout); testConnectionProtocol(urlConnection); HttpDownloadCountingOutputStream.this.is = localUrl.openStream(); String s = urlConnection.getHeaderField("Content-Length"); s_logger.info("Content-lenght: " + s); setTotalBytes(s != null ? Integer.parseInt(s) : -1); postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), 0, HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.IN_PROGRESS, null); int bufferSize = getBufferSize(); if (bufferSize == 0 && getTotalBytes() > 0) { int newSize = Math.round(HttpDownloadCountingOutputStream.this.totalBytes / 100 * 1); bufferSize = newSize; setBufferSize(newSize); } else if (bufferSize == 0) { int newSize = 1024 * 4; bufferSize = newSize; setBufferSize(newSize); } long numBytes = IOUtils.copyLarge(HttpDownloadCountingOutputStream.this.is, HttpDownloadCountingOutputStream.this, new byte[bufferSize]); postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), numBytes, HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.COMPLETED, null); } catch (IOException e) { postProgressEvent(HttpDownloadCountingOutputStream.this.options.getClientId(), getByteCount(), HttpDownloadCountingOutputStream.this.totalBytes, DOWNLOAD_STATUS.FAILED, e.getMessage()); throw new KuraConnectException(e); } finally { if (HttpDownloadCountingOutputStream.this.is != null) { try { HttpDownloadCountingOutputStream.this.is.close(); } catch (IOException e) { } } try { close(); } catch (IOException e) { } localUrl = null; if (shouldAuthenticate) { Authenticator.setDefault(null); } } return null; } }); try { this.future.get(); } catch (ExecutionException ex) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex); } catch (InterruptedException ex) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex); } }
From source file:uk.ac.ucl.cs.cmic.giftcloud.restserver.GiftCloudLoginDialog.java
public PasswordAuthentication getPasswordAuthentication(final String prompt) { // Set the default background colour to white UIManager UI = new UIManager(); UI.put("OptionPane.background", Color.white); UI.put("Panel.background", Color.white); String defaultUserName = ""; if (giftCloudProperties.getLastUserName().isPresent()) { defaultUserName = giftCloudProperties.getLastUserName().get(); }// ww w .j ava2 s .c o m // Create a panel for entering username and password final JPanel usernamePasswordPanel = new JPanel(new GridBagLayout()); final JLabel promptField = new JLabel(prompt, SwingConstants.CENTER); final JTextField usernameField = new JTextField(defaultUserName, 16); final JPasswordField passwordField = new JPasswordField(16); // Add a special listener to get the focus onto the username field when the component is created, or password if the username has already been populated from the default value if (StringUtils.isBlank(defaultUserName)) { usernameField.addAncestorListener(new RequestFocusListener()); } else { passwordField.addAncestorListener(new RequestFocusListener()); } usernamePasswordPanel.add(promptField, promptConstraint); usernamePasswordPanel.add(new JLabel("Username:"), labelConstraint); usernamePasswordPanel.add(usernameField, fieldConstraint); usernamePasswordPanel.add(new JLabel("Password:"), labelConstraint); usernamePasswordPanel.add(passwordField, fieldConstraint); // Show the login dialog final int returnValue = JOptionPane.showConfirmDialog(new JDialog(getFrame(parent)), usernamePasswordPanel, LOGIN_DIALOG_TITLE, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon); if (JOptionPane.OK_OPTION == returnValue) { giftCloudProperties.setLastUserName(usernameField.getText()); giftCloudProperties.setLastPassword(passwordField.getPassword()); giftCloudProperties.save(); return new PasswordAuthentication(usernameField.getText(), passwordField.getPassword()); } else { return null; } }
From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java
@Override public void signalProcess(long processInstanceId, String signalType, Object event) throws WorkflowException { HttpURLConnection connection = null; Governance governance = new Governance(); final String username = governance.getOverlordUser(); final String password = governance.getOverlordPassword(); Authenticator.setDefault(new Authenticator() { @Override/* w w w.j a va2s . com*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); } }); try { String urlStr = governance.getGovernanceUrl() + String.format("/rest/process/signal/%s/%s/%s", processInstanceId, signalType, event); //$NON-NLS-1$ URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("PUT"); //$NON-NLS-1$ connection.setConnectTimeout(60000); connection.setReadTimeout(60000); connection.connect(); int responseCode = connection.getResponseCode(); if (!(responseCode >= 200 && responseCode < 300)) { 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(); } }