private void prepareAuthentication() { // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6626700 // The credentials from earlier requests are cached, and used if // the current ones doesn't work!!! AuthCacheValue.setAuthCache(new AuthCacheImpl()); if (username != null && password != null) { Authenticator.setDefault(new HTTPBasicAuthenticator(username, password)); } // remove the current entry else { Authenticator.setDefault(null); } }
public Request authenticateProxy(Proxy paramProxy, Response paramResponse) { List localList = paramResponse.challenges(); paramResponse = paramResponse.request(); URL localURL = paramResponse.url(); int i = 0; int j = localList.size(); while (i < j) { Object localObject = (Challenge) localList.get(i); if ("Basic".equalsIgnoreCase(((Challenge) localObject).getScheme())) { InetSocketAddress localInetSocketAddress = (InetSocketAddress) paramProxy.address(); localObject = java.net.Authenticator.requestPasswordAuthentication( localInetSocketAddress.getHostName(), getConnectToInetAddress(paramProxy, localURL), localInetSocketAddress.getPort(), localURL.getProtocol(), ((Challenge) localObject).getRealm(), ((Challenge) localObject).getScheme(), localURL, Authenticator.RequestorType.PROXY); if (localObject != null) { paramProxy = Credentials.basic( ((PasswordAuthentication) localObject).getUserName(), new String(((PasswordAuthentication) localObject).getPassword())); return paramResponse.newBuilder().header("Proxy-Authorization", paramProxy).build(); } } i += 1; } return null; }
void doit() { String username = args.Username; String password = args.Password; if (username != null || password != null) Authenticator.setDefault(new MyAuthenticator(username, password)); System.setProperty("java.protocol.handler.pkgs", "edu.mscd.cs"); String[] add = args.additional; if (add == null) { logger.warning("No URLs specified, exiting"); System.exit(1); } /* ** add the specified URLs to the list to be fetched. */ String[] t = new String[add.length]; for (int i = 0; i < add.length; i++) { t[i] = "<a href=\"" + add[i] + "\">"; } /* ** add to the URLs, with no base */ addToURLs(null, t); fetchAll(); /* ** shall we save the cookies to a file? */ String savecookies = args.SaveCookies; if (savecookies != null) cookies.saveCookies(savecookies); }
public String classifyUrl(String pageURL) { try { URL url = new URL(pageURL); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("202.141.80.22", 3128)); Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication("b.revanth", "batman9903".toCharArray())); } }; Authenticator.setDefault(authenticator); URLConnection urlConnection = url.openConnection(proxy); urlConnection.connect(); String line = null; StringBuffer webPageBuffer = new StringBuffer(); BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = inputReader.readLine()) != null) { webPageBuffer.append(line); } Document document = Jsoup.parse(String.valueOf(webPageBuffer), "UTF-8"); Elements title = document.select("title"); Elements body = document.select("body"); Log.i("Now Classifying ", pageURL); String assignedClass = classifyText(title.text() + "\n" + body.text()); return assignedClass; } catch (IOException e) { Log.i("Error:", e.toString()); e.printStackTrace(); } return "N/A"; }
public static void main(String[] args) throws Exception { // assume NTLM is not supported when Kerberos is not available try { Class.forName("javax.security.auth.kerberos.KerberosPrincipal"); System.out.println("Kerberos is present, assuming NTLM is supported too"); return; } catch (ClassNotFoundException okay) { } // setup Authenticator Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user", "pass".toCharArray()); } }); // test combinations of authentication schemes test("Basic"); test("Digest"); test("Basic", "Digest"); test("Basic", "NTLM"); test("Digest", "NTLM"); test("Basic", "Digest", "NTLM"); // test NTLM only, this should fail with "401 Unauthorized" testNTLM(); System.out.println(); System.out.println("TEST PASSED"); }
@Test public void shouldNotServeContentToUserWithoutConnectRole() throws Exception { // Configured in pom final String login = "******"; final String password = "******"; Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(login, password.toCharArray()); } }); URL postUrl = new URL(SERVER_URL + "/"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_UNAUTHORIZED)); connection.disconnect(); }
/** * Returns the authorization credentials on the base of provided authorization challenge * * @param challenge * @return authorization credentials * @throws IOException */ private String getAuthorizationCredentials(String challenge) throws IOException { int idx = challenge.indexOf(" "); // $NON-NLS-1$ String scheme = challenge.substring(0, idx); int realm = challenge.indexOf("realm=\"") + 7; // $NON-NLS-1$ String prompt = null; if (realm != -1) { int end = challenge.indexOf('"', realm); if (end != -1) { prompt = challenge.substring(realm, end); } } // The following will use the user-defined authenticator to get // the password PasswordAuthentication pa = Authenticator.requestPasswordAuthentication( getHostAddress(), getHostPort(), url.getProtocol(), prompt, scheme); if (pa == null) { // could not retrieve the credentials return null; } // base64 encode the username and password byte[] bytes = (pa.getUserName() + ":" + new String(pa.getPassword())) // $NON-NLS-1$ .getBytes("ISO8859_1"); // $NON-NLS-1$ String encoded = Base64.encode(bytes, "ISO8859_1"); // $NON-NLS-1$ return scheme + " " + encoded; // $NON-NLS-1$ }
private void checkProxy() { if (null != System.getProperty("http.proxyHost") || null != System.getProperty("https.proxyHost")) { Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { String prot = getRequestingProtocol().toLowerCase(); String host = System.getProperty(prot + ".proxyHost", ""); String port = System.getProperty(prot + ".proxyPort", ""); String user = System.getProperty(prot + ".proxyUser", ""); String password = System.getProperty(prot + ".proxyPassword", ""); if (getRequestingHost().toLowerCase().equals(host.toLowerCase())) { if (Integer.parseInt(port) == getRequestingPort()) { return new PasswordAuthentication(user, password.toCharArray()); } } } return null; } }); } }
int invokeOperation(String operation) { Authenticator.setDefault(getAuthenticator()); String urlString = getInvokeUrl() + "&operation=" + operation; try { URL invoke = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) invoke.openConnection(); connection.setReadTimeout(getHttpRequestReadTimeout()); InputStream in = connection.getInputStream(); int ch; while ((ch = in.read()) != -1) { System.out.write((char) ch); } in.close(); System.out.println(""); System.out.flush(); } catch (final ConnectException e) { LOG.error("error when attempting to fetch URL \"{}\"", urlString, e); if (isVerbose()) { System.out.println(e.getMessage() + " when attempting to fetch URL \"" + urlString + "\""); } return 1; } catch (final Throwable t) { LOG.error("error invoking {} operation", operation, t); System.out.println("error invoking " + operation + " operation"); return 1; } return 0; }
private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection con = null; if (isSetProxy && proxyHost != null && !proxyHost.equals("")) { log("Proxy : " + proxyHost); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { log("Proxy AuthUser: "******"Proxy AuthPassword: "******"Opening proxied connection(" + proxyHost + ":" + proxyPort + ")"); con = (HttpURLConnection) new URL(url).openConnection(proxy); } else { con = (HttpURLConnection) new URL(url).openConnection(); } if (connectionTimeout > 0 && !isJDK14orEarlier) { con.setConnectTimeout(connectionTimeout); } if (readTimeout > 0 && !isJDK14orEarlier) { con.setReadTimeout(readTimeout); } return con; }
@Test public void testProxyAuthGet() throws Exception { JettyProxyProvider proxy = new JettyProxyProvider("u", "p"); proxy.addBehaviour("/*", new Debug(), new Content()); proxy.start(); URL url = new URL("http://speutel.invalid/foo"); SocketAddress sa = new InetSocketAddress("localhost", proxy.getPort()); Proxy p = new Proxy(Type.HTTP, sa); Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestingHost().equals("localhost")) { String password = "******"; return new PasswordAuthentication("u", password.toCharArray()); } return super.getPasswordAuthentication(); } }); HttpURLConnection conn = (HttpURLConnection) url.openConnection(p); conn.setDoInput(true); conn.connect(); assertEquals(200, conn.getResponseCode()); assertEquals("foo", read(conn.getContent()).trim()); conn.disconnect(); }
/** * @param args * @throws GeneralSecurityException * @throws IOException */ public static void main(String[] args) throws GeneralSecurityException, IOException { final String rpcuser = "******"; // RPC User name (set in config) final String rpcpassword = "******"; // RPC Pass (set in config) Authenticator.setDefault( new Authenticator() { // This sets the default authenticator, with the set username and // password protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(rpcuser, rpcpassword.toCharArray()); } }); while (true) { Work work = getwork(); // Gets the work from the server String data = work.result.data; // Gets the data to hash from the work String target = work.result.target; // Gets the target from the work String realdata = data.substring(0, 160); byte[] databyte = endianSwitch(Converter.fromHexString(realdata)); // Converts the target string to a byte array for easier comparison byte[] targetbyte = Converter.fromHexString(target); System.out.println(printByteArray(targetbyte)); if (doScrypt( databyte, targetbyte)) { // Calls sCrypt with the proper parameters, and returns the correct data work.result.data = printByteArray(endianSwitch(databyte)) + data.substring(160, 256); System.out.println(sendWork(work)); // Send the work } } }
/** * This method is called upon plug-in activation * * @param context * @throws Exception */ public void start(BundleContext context) throws Exception { super.start(context); iconsUrl = context.getBundle().getEntry(ICONS_PATH); Authenticator.setDefault(new UDIGAuthenticator()); /* * TODO Further code can nuke the previously set authenticator. Proper security access * should be configured to prevent this. */ disableCerts(); try { loadVersion(); java.lang.System.setProperty( "http.agent", "uDig " + getVersion() + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ java.lang.System.setProperty( "https.agent", "uDig " + getVersion() + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (Throwable e) { log("error determining version", e); // $NON-NLS-1$ } }
/* * Enabled aggressive block sorting */ @Override public Request authenticateProxy(Proxy object, Response object2) throws IOException { List<Challenge> list = object2.challenges(); object2 = object2.request(); URL uRL = object2.url(); int n2 = 0; int n3 = list.size(); while (n2 < n3) { InetSocketAddress inetSocketAddress; Object object3 = list.get(n2); if ("Basic".equalsIgnoreCase(object3.getScheme()) && (object3 = java.net.Authenticator.requestPasswordAuthentication( (inetSocketAddress = (InetSocketAddress) object.address()).getHostName(), this.getConnectToInetAddress((Proxy) object, uRL), inetSocketAddress.getPort(), uRL.getProtocol(), object3.getRealm(), object3.getScheme(), uRL, Authenticator.RequestorType.PROXY)) != null) { object = Credentials.basic(object3.getUserName(), new String(object3.getPassword())); return object2.newBuilder().header("Proxy-Authorization", (String) object).build(); } ++n2; } return null; }
protected HttpURLConnection getConnection(String s) { if (isProxyConfigured()) { if (CONF.getHttpProxyUser() != null && !CONF.getHttpProxyUser().equals("")) { if (logger.isDebugEnabled()) { logger.debug((new StringBuilder("Proxy AuthUser: "******"Proxy AuthPassword: "******"Opening proxied connection(")).append(CONF.getHttpProxyHost()).append(":").append(CONF.getHttpProxyPort()).append(")").toString()); } s = (HttpURLConnection)(new URL(s)).openConnection(proxy); } else { s = (HttpURLConnection)(new URL(s)).openConnection(); } if (CONF.getHttpConnectionTimeout() > 0) { s.setConnectTimeout(CONF.getHttpConnectionTimeout()); } if (CONF.getHttpReadTimeout() > 0) { s.setReadTimeout(CONF.getHttpReadTimeout()); } s.setInstanceFollowRedirects(false); return s; }
/** * Returns the authorization credentials that may satisfy the challenge. Returns null if a * challenge header was not provided or if credentials were not available. */ private static String getCredentials( RawHeaders responseHeaders, String challengeHeader, Proxy proxy, URL url) throws IOException { List<Challenge> challenges = parseChallenges(responseHeaders, challengeHeader); if (challenges.isEmpty()) { return null; } for (Challenge challenge : challenges) { // Use the global authenticator to get the password. PasswordAuthentication auth; if (responseHeaders.getResponseCode() == HTTP_PROXY_AUTH) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); auth = Authenticator.requestPasswordAuthentication( proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(), challenge.realm, challenge.scheme, url, Authenticator.RequestorType.PROXY); } else { auth = Authenticator.requestPasswordAuthentication( url.getHost(), getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(), challenge.realm, challenge.scheme, url, Authenticator.RequestorType.SERVER); } if (auth == null) { continue; } // Use base64 to encode the username and password. String usernameAndPassword = auth.getUserName() + ":" + new String(auth.getPassword()); byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1"); String encoded = Base64.encode(bytes); return challenge.scheme + " " + encoded; } return null; }
private HttpURLConnection getConnection(final String url_string) throws IOException { final HttpURLConnection con; final Proxy proxy; if (isProxyConfigured()) { if (CONF.getHttpProxyUser() != null && !CONF.getHttpProxyUser().equals("")) { if (logger.isDebugEnabled()) { logger.debug("Proxy AuthUser: "******"Proxy AuthPassword: "******"Opening proxied connection(" + CONF.getHttpProxyHost() + ":" + CONF.getHttpProxyPort() + ")"); } } else { proxy = Proxy.NO_PROXY; } final URL url = new URL(url_string); con = (HttpURLConnection) url.openConnection(proxy); if (CONF.getHttpConnectionTimeout() > 0) { con.setConnectTimeout(CONF.getHttpConnectionTimeout()); } if (CONF.getHttpReadTimeout() > 0) { con.setReadTimeout(CONF.getHttpReadTimeout()); } con.setInstanceFollowRedirects(false); if (con instanceof HttpsURLConnection && CONF.isSSLErrorIgnored()) { ((HttpsURLConnection) con).setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER); if (IGNORE_ERROR_SSL_FACTORY != null) { ((HttpsURLConnection) con).setSSLSocketFactory(IGNORE_ERROR_SSL_FACTORY); } } return con; }
private void setupProxy(final BundleContext context) { final ServiceReference proxy; proxy = context.getServiceReference(IProxyService.class.getName()); if (proxy != null) { ProxySelector.setDefault(new EclipseProxySelector((IProxyService) context.getService(proxy))); Authenticator.setDefault(new EclipseAuthenticator((IProxyService) context.getService(proxy))); } }
private static void authenticate(final String username, final String password) { Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); } }); }
public static void main(String args[]) throws IOException, DDSException, ParseException, DODSException { Authenticator.setDefault(new MyAuthenticator()); String urlName = "http://iridl.ldeo.columbia.edu/expert/SOURCES/.IMD/.RF0p5/.gridded/.daily/.v1p0/.rf/dup/SOURCES/.Features/.Political/.World/.1st_Order/.the_geom/objectid/%281033%29VALUES/rasterize/0.5/maskle/dataflag/0/maskle/mul/dods"; // String urlName = // "http://iridl.ldeo.columbia.edu/expert/SOURCES/.WCRP/.GCOS/.GPCC/.FDP/.version4/.2p5/.prcp/SOURCES/.Features/.Political/.World/.Countries/.the_geom/objectid/146/VALUE%5BX/Y%5Dweighted-average/T/%28Jan%201961%29%28Dec%202007%29RANGE/yearly-anomalies/T/12/boxAverage/T/12/STEP/dods"; // String urlName = // "http://iridl.ldeo.columbia.edu/SOURCES/.IMD/.RF0p5/.gridded/.daily/.v1p0/.rf/a:/:a:/SOURCES/.Features/.Political/.World/.1st_Order/.the_geom/objectid/%281033%29VALUES/:a/rasterize/0.5/maskle/dataflag/0/maskle/mul/T/%28Jul-Sep%29VALUES/dods"; doit(urlName); }
/** * A function that set the proxy * * @param ip server IP * @param port port number * @param user user name for authentication * @param pw user password for authentication */ public void setProxy(String ip, String port, String user, String pw) { System.setProperty("proxySet", "true"); System.setProperty("http.proxyHost", ip); System.setProperty("http.proxyPort", port); Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pw.toCharArray()); } }); }
@Ignore public void testGetInfoTask() throws InterruptedException, ExecutionException { Authenticator.setDefault(new DcAuthenticator("*****@*****.**", "user")); ExecutorService execSvc = Executors.newFixedThreadPool(1); GetInfoTask task = new GetInfoTask(Global.getBagUploadUri(), PID); task.addProgressListener(getProgressListener()); Future<ClientResponse> pidInfoResp = execSvc.submit(task); assertNotNull(pidInfoResp); assertNotNull( "No response received from server. Check if the server's up and running.", pidInfoResp.get()); LOGGER.info("HTTP Status: {}", pidInfoResp.get().getStatus()); }
private String fetchForUser(String template, final SyncableUser actionable, SQLiteDatabase database) { try { URL url = new URL(template); final Pair<String, String> credentials = HubApplication._().getCredentials(); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(credentials.first, credentials.second.toCharArray()); } }); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); WebUtil.setupGetConnection(conn, credentials); int response = conn.getResponseCode(); ServicesMonitor.reportMessage("HTTP Record Request for " + actionable.getUsername() + " response code: " + response); if(response >= 500) { actionable.updateStatus(SyncableUser.UserStatus.AuthError); actionable.writeToDb(database); ServicesMonitor.reportMessage("Error fetching user data" + conn.getResponseMessage()); return null; } else if(response >= 400) { actionable.updateStatus(SyncableUser.UserStatus.AuthError); actionable.writeToDb(database); return null; } else if(response == 200) { try { String guid = UUID.randomUUID().toString(); InputStream responseStream = new BufferedInputStream(conn.getInputStream()); StreamsUtil.writeFromInputToOutput(responseStream, context.openFileOutput(guid, Context.MODE_PRIVATE)); return guid; } catch(IOException e) { e.printStackTrace(); ServicesMonitor.reportMessage("Error downloading user record " + e.getMessage()); } } }catch( IOException ioe) { } return null; }
private InputStream getInputProxyStream(String URLName) throws PackageManagerException { try { Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", ProxyProperties.getProxyHost()); systemSettings.put("http.proxyPort", ProxyProperties.getProxyPort()); System.setProperties(systemSettings); Authenticator.setDefault( new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( ProxyProperties.getProxyAccount(), ProxyProperties.getProxyPassword().toCharArray()); } }); URL u = new URL(URLName); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.connect(); return con.getInputStream(); } catch (Exception e) { e.printStackTrace(); if (null != pm) { pm.addWarning( PreferenceStoreHolder.getPreferenceStoreByName("Screen") .getPreferenceAsString( "ProxyManager.getInputStreamByProxy.IOException.connect", "No Entry for ProxyManager.getInputStreamByProxy.IOException.connect found")); logger.error( PreferenceStoreHolder.getPreferenceStoreByName("Screen") .getPreferenceAsString( "ProxyManager.getInputStreamByProxy.IOException.connect", "No Entry for ProxyManager.getInputStreamByProxy.IOException.connect found"), e); } else logger.error( PreferenceStoreHolder.getPreferenceStoreByName("Screen") .getPreferenceAsString( "ProxyManager.getInputStreamByProxy.IOException.connect", "No Entry for ProxyManager.getInputStreamByProxy.IOException.connect found"), e); throw new PackageManagerException( PreferenceStoreHolder.getPreferenceStoreByName("Screen") .getPreferenceAsString( "ProxyManager.getInputStreamByProxy.IOException.connect", "No Entry for ProxyManager.getInputStreamByProxy.IOException.connect found"), e); } }
private static PasswordAuthentication getSystemCreds( final AuthScope authscope, final Authenticator.RequestorType requestorType) { final String hostname = authscope.getHost(); final int port = authscope.getPort(); final String protocol = port == 443 ? "https" : "http"; return Authenticator.requestPasswordAuthentication( hostname, null, port, protocol, null, translateScheme(authscope.getScheme()), null, requestorType); }
@Before public void beforeEach() { // Configured in pom final String login = "******"; final String password = "******"; Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(login, password.toCharArray()); } }); }
/** Set default proxy settings, used by cobra for ie */ public static synchronized void setDefaultProxySettings() { String sProxyHost = ConfigurationManager.getProperty(CONF_NETWORK_PROXY_HOSTNAME); int iProxyPort = ConfigurationManager.getInt(CONF_NETWORK_PROXY_PORT); String sProxyLogin = ConfigurationManager.getProperty(CONF_NETWORK_PROXY_LOGIN); String sProxyPwd = ConfigurationManager.getProperty(CONF_NETWORK_PROXY_PWD); Type proxyType = Type.DIRECT; if (ConfigurationManager.getBoolean(CONF_NETWORK_USE_PROXY)) { // Set default proxy value if (PROXY_TYPE_HTTP.equals(ConfigurationManager.getProperty(CONF_NETWORK_PROXY_TYPE))) { proxyType = Type.HTTP; } else if (PROXY_TYPE_SOCKS.equals( ConfigurationManager.getProperty(CONF_NETWORK_PROXY_TYPE))) { proxyType = Type.SOCKS; } try { proxy = new Proxy(proxyType, sProxyHost, iProxyPort, sProxyLogin, sProxyPwd); } catch (Exception e) { Log.error(e); return; } } // Set system defaults proxy values, if we don't use DownloadManager // methods // see http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html if (ConfigurationManager.getBoolean(CONF_NETWORK_USE_PROXY)) { System.getProperties().put("proxySet", "true"); if (PROXY_TYPE_HTTP.equals(ConfigurationManager.getProperty(CONF_NETWORK_PROXY_TYPE))) { System.setProperty("http.proxyHost", sProxyHost); System.setProperty("http.proxyPort", Integer.toString(iProxyPort)); } else if (PROXY_TYPE_SOCKS.equals( ConfigurationManager.getProperty(CONF_NETWORK_PROXY_TYPE))) { System.setProperty("socksProxyHost", sProxyHost); System.setProperty("socksProxyPort ", Integer.toString(iProxyPort)); } Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String user = ConfigurationManager.getProperty(CONF_NETWORK_PROXY_LOGIN); char[] pwd = Util.rot13(ConfigurationManager.getProperty(CONF_NETWORK_PROXY_PWD)) .toCharArray(); return new PasswordAuthentication(user, pwd); } }); } }
public void setUserIDPassword(String user_id, String password) { if (password_authentication == null) { Authenticator.setDefault( new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { if (url != null && url.equals(getRequestingURL().toString())) { if (interactive_mode) { System.out.println("\nHTTP Authentication Request: " + url); } return password_authentication; } return null; } }); } password_authentication = new PasswordAuthentication(user_id, password.toCharArray()); }
private static void setupNetworking() { final Preferences auth = Preferences.userRoot().node(NetworkAuthenticator.NODEHTTP); if (auth.getBoolean(NetworkAuthenticator.USEPROXY, false)) { final String proxyHost = auth.get(NetworkAuthenticator.PROXYHOST, ""); final String proxyPort = auth.get(NetworkAuthenticator.PROXYPORT, ""); System.getProperties().put("http.proxyHost", proxyHost); System.getProperties().put("http.proxyPort", proxyPort); // this will deal with any authentication requests properly Authenticator.setDefault(new NetworkAuthenticator()); System.out.println(ResourceUtils.getString("Message.Proxy") + proxyHost + ":" + proxyPort); } }
public static void main(String args[]) { JFrame frame; final DatasetEditor editor = new DatasetEditor(); frame = new JFrame("Test DatasetEditor"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JButton save = new JButton("Accept"); save.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { editor.accept(); editor.store2Dataset(); try { cat.writeXML(System.out, true); } catch (IOException e1) { e1.printStackTrace(); } } }); JPanel main = new JPanel(new BorderLayout()); main.add(editor, BorderLayout.CENTER); main.add(save, BorderLayout.NORTH); frame.getContentPane().add(main); frame.pack(); frame.setLocation(150, 10); frame.setVisible(true); // LOOK-NOSAVE java.net.Authenticator.setDefault(new UrlAuthenticatorDialog(frame)); // String url = "http://uni10.unidata.ucar.edu:8088/thredds/content/idd/models.xml"; String url = "http://thredds.ucar.edu/thredds/content/idd/models.xml"; InvCatalogFactory catFactory = InvCatalogFactory.getDefaultFactory(true); cat = catFactory.readXML(url); InvDatasetImpl ds = (InvDatasetImpl) cat.findDatasetByID("NCEP/NAM/V"); editor.setDataset(ds); }