List of usage examples for java.net Authenticator setDefault
public static synchronized void setDefault(Authenticator a)
From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java
private HttpURLConnection createConnection(String wsPart, String method) throws Exception { Authenticator.setDefault(new Authenticator() { @Override//from ww w . jav a 2 s . co m protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(LOGIN, PWD.toCharArray()); } }); final URL url = new URL(getOpenbravoURL() + wsPart); final HttpURLConnection hc = (HttpURLConnection) url.openConnection(); hc.setRequestMethod(method); hc.setAllowUserInteraction(false); hc.setDefaultUseCaches(false); hc.setDoOutput(true); hc.setDoInput(true); hc.setInstanceFollowRedirects(true); hc.setUseCaches(false); hc.setRequestProperty("Content-Type", "text/xml"); return hc; }
From source file:sce.RESTKBJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {/* w ww . j a v a 2 s.co m*/ JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); String url = jobDataMap.getString("#url"); if (url == null) { throw new JobExecutionException("#url parameter 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(); Document document = docBuilder.parse(this.urlConnection.getInputStream()); parseKBResponse(document.getDocumentElement(), context); //set of the result is done in the method parseKBresponse, because it is built invoking it iteratively //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:info.joseluismartin.gtc.mvc.CacheController.java
public void init() throws ServletException { List<ProxyConfig> list = proxyService.getAll(); if (!list.isEmpty()) { ProxyConfig config = list.get(0); if (!config.isDirectConnection()) { proxyHost = config.getHost(); proxyPort = config.getPort(); proxyUser = config.getUserName(); proxyPassword = config.getPassword(); SocketAddress address = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); Authenticator.setDefault(new SimpleAuthenticator(proxyUser, proxyPassword)); log.info("Using proxy: " + proxyHost + ":" + proxyPort); }/*from www . j a v a2 s .co m*/ } }
From source file:org.getobjects.appserver.core.WOHTTPConnection.java
public boolean sendRequest(WORequest _rq) { if (_rq == null) return false; try {/*from w w w .j av a2 s. com*/ URL rqURL = new URL(this.url, _rq.uri()); boolean needsSetup = true; if (this.urlConnection != null && this.urlConnection.getURL().equals(rqURL)) { needsSetup = false; } if (needsSetup) { this.urlConnection = (HttpURLConnection) rqURL.openConnection(); this.setupHttpURLConnection(this.urlConnection); if (this.urlConnection instanceof HttpsURLConnection) { this.setupHttpsURLConnection((HttpsURLConnection) this.urlConnection); } } // unfortunately there's no better API... Authenticator.setDefault(this.authenticator()); // set properties and headers this.urlConnection.setRequestMethod(_rq.method()); this.urlConnection.setInstanceFollowRedirects(this.followRedirects); for (String headerKey : _rq.headerKeys()) { List<String> headers = _rq.headersForKey(headerKey); if (UObject.isNotEmpty(headers)) { String headerProp = UString.componentsJoinedByString(headers, " , "); this.urlConnection.setRequestProperty(headerKey, headerProp); } } String connectionProp = this.keepAlive ? "keep-alive" : "close"; this.urlConnection.setRequestProperty("connection", connectionProp); byte[] content = _rq.content(); boolean hasContent = UObject.isNotEmpty(content); // NOTE: setting doOutput(true) has the effect of also setting // the request method to POST? WTF? this.urlConnection.setDoOutput(hasContent); if (hasContent) { // send content body OutputStream os = this.urlConnection.getOutputStream(); os.write(content); os.close(); } else { this.urlConnection.connect(); } // save request for response this.request = _rq; return true; } catch (Exception e) { log.error("sendRequest() failed: " + e); return false; } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPAuthenticatorIT.java
@Before @After/*from w w w . j a v a 2 s . c o m*/ public void resetAuthenticator() throws CMException { Authenticator.setDefault(new NullAuthenticator()); HTTPAuthenticatorServiceUsernameAndPasswordProvider.resetCalls(); }
From source file:org.panlab.tgw.restclient.RepoAdapter.java
public static ResourceInstance getResourceInstance(String type) { Client c = Client.create();/*from w w w . j a v a 2 s. com*/ c.setFollowRedirects(true); Authenticator.setDefault(new PwdAuthenticator()); WebResource r = c.resource("http://repos.pii.tssg.org:8080/repository/rest/resourceInstance/"); String resp = r.get(String.class); //System.out.println(resp); resp = addSchemaDefinition(resp); try { ListDocument lDoc = ListDocument.Factory.parse(resp); ResourceInstance[] riArray = lDoc.getList().getResourceInstanceArray(); for (int i = 0; i < riArray.length; i++) if (riArray[i].isSetCommonName() && riArray[i].getCommonName().equalsIgnoreCase(type)) return riArray[i]; } catch (XmlException ex) { ex.printStackTrace(); return null; } return null; }
From source file:org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.java
private void configureProxy() { // It seems there is no way to set a proxy provider type (manual, native or // direct) without the Eclipse UI. // The org.eclipse.core.net plugin removes the http., https. system properties // when setting its preferences and a proxy provider isn't manual. // We save these parameters and set them after starting the // org.eclipse.core.net plugin. String httpHost = System.getProperty(HTTP_PROXY_HOST); String httpPort = System.getProperty(HTTP_PROXY_PORT); String httpUser = System.getProperty(HTTP_PROXY_USER); String httpPassword = System.getProperty(HTTP_PROXY_PASSWORD); String httpsHost = System.getProperty(HTTPS_PROXY_HOST); String httpsPort = System.getProperty(HTTPS_PROXY_PORT); String httpsUser = System.getProperty(HTTPS_PROXY_USER); String httpsPassword = System.getProperty(HTTPS_PROXY_PASSWORD); String httpsNonProxyHosts = System.getProperty(HTTPS_NON_PROXY_HOSTS); String httpNonProxyHosts = System.getProperty(HTTP_NON_PROXY_HOSTS); if (StringUtils.isNotBlank(httpUser) || StringUtils.isNotBlank(httpsUser)) { try {/*from w ww . j av a 2s . c o m*/ Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT); } catch (BundleException e) { logException(e.getMessage(), e); } if (StringUtils.isNotBlank(httpUser) && StringUtils.isNotBlank(httpPassword)) { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(httpUser, httpPassword.toCharArray()); } }); } IProxyService proxyService = getProxyService(); if (proxyService != null) { ProxySelector.setActiveProvider(MANUAL); IProxyData[] proxies = proxyService.getProxyData(); for (IProxyData proxy : proxies) { if ("HTTP".equals(proxy.getType())) { proxy.setHost(httpHost); proxy.setPort(httpPort == null ? -1 : Integer.valueOf(httpPort)); proxy.setPassword(httpPassword); proxy.setUserid(httpUser); } if ("HTTPS".equals(proxy.getType())) { proxy.setHost(httpsHost); proxy.setPort(httpsPort == null ? -1 : Integer.valueOf(httpsPort)); proxy.setPassword(httpsPassword); proxy.setUserid(httpsUser); } } try { proxyService.setProxyData(proxies); if (httpHost != null) { System.setProperty(HTTP_PROXY_HOST, httpHost); } if (httpPort != null) { System.setProperty(HTTP_PROXY_PORT, httpPort); } if (httpUser != null) { System.setProperty(HTTP_PROXY_USER, httpUser); } if (httpPassword != null) { System.setProperty(HTTP_PROXY_PASSWORD, httpPassword); } if (httpsHost != null) { System.setProperty(HTTPS_PROXY_HOST, httpsHost); } if (httpsPort != null) { System.setProperty(HTTPS_PROXY_PORT, httpsPort); } if (httpsUser != null) { System.setProperty(HTTPS_PROXY_USER, httpsUser); } if (httpsPassword != null) { System.setProperty(HTTPS_PROXY_PASSWORD, httpsPassword); } if (httpsNonProxyHosts != null) { System.setProperty(HTTPS_NON_PROXY_HOSTS, httpsNonProxyHosts); } if (httpNonProxyHosts != null) { System.setProperty(HTTP_NON_PROXY_HOSTS, httpNonProxyHosts); } } catch (CoreException e) { logException(e.getMessage(), e); } } } }
From source file:org.drools.guvnor.server.files.PackageDeploymentServletChangeSetIntegrationTest.java
@Test @RunAsClient/*from w w w . j ava 2 s. c o m*/ public void downloadPackageWithHttpClientImpl(@ArquillianResource URL baseURL) throws IOException, ClassNotFoundException { URL url = new URL(baseURL, "org.drools.guvnor.Guvnor/package/downloadPackageWithHttpClientImpl/snapshotC1"); Resource resource = ResourceFactory.newUrlResource(url); KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("admin", "admin".toCharArray()); } }); InputStream in = null; Collection<KnowledgePackage> kpkgs = null; try { in = resource.getInputStream(); Object object = DroolsStreamUtils.streamIn(in); if (object instanceof Collection) { kpkgs = (Collection<KnowledgePackage>) object; } else if (object instanceof KnowledgePackageImp) { kpkgs = Collections.singletonList((KnowledgePackage) object); } else if (object instanceof Package) { kpkgs = Collections.singletonList((KnowledgePackage) new KnowledgePackageImp((Package) object)); } else if (object instanceof Package[]) { kpkgs = new ArrayList<KnowledgePackage>(); for (Package pkg : (Package[]) object) { kpkgs.add(new KnowledgePackageImp(pkg)); } } else { throw new RuntimeException("Unknown binary format trying to load resource " + resource.toString()); } } finally { IOUtils.closeQuietly(in); } assertNotNull(kpkgs); assertFalse(kpkgs.isEmpty()); assertNotNull(kpkgs.iterator().next()); }
From source file:org.polymap.core.CorePlugin.java
public void start(final BundleContext context) throws Exception { super.start(context); log.debug("start..."); plugin = this; Authenticator.setDefault(new DialogAuthenticator()); System.setProperty("http.agent", "Polymap3 (http://polymap.org/polymap3/)"); System.setProperty("https.agent", "Polymap3 (http://polymap.org/polymap3/)"); // RAP session context this.rapSessionContextProvider = new RapSessionContextProvider(); SessionContext.addProvider(rapSessionContextProvider); // init HttpServiceTracker httpServiceTracker = new HttpServiceTracker(context); httpServiceTracker.open();//from w w w . j a va 2s.co m }
From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.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 {// ww w.j a v a 2 s . co m dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { Logger.getLogger(ProgettiHwSwEthv2.class.getName()).log(Level.SEVERE, null, ex); } 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()) + "/protect/" + GET_STATUS_URL; } else { statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort()) + "/" + GET_STATUS_URL; } LOG.info("ProgettiHwSwEth gets relay status from file " + statusFileURL); doc = dBuilder.parse(new URL(statusFileURL).openStream()); doc.getDocumentElement().normalize(); } catch (ConnectException connEx) { disconnect(); this.stop(); this.setDescription("Connection timed out, no reply from the board at " + statusFileURL); } catch (SAXException ex) { disconnect(); this.stop(); LOG.severe(Freedomotic.getStackTraceInfo(ex)); } catch (Exception ex) { disconnect(); this.stop(); setDescription("Unable to connect to " + statusFileURL); LOG.severe(Freedomotic.getStackTraceInfo(ex)); } return doc; }