List of usage examples for java.net Authenticator Authenticator
Authenticator
From source file:sce.RESTJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {//from ww w . j av a 2 s.c o 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
/** * *///from w w w . j a v a 2 s . c o m 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: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 www . j a v a2 s.c o m 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: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/*from w w w.ja v a 2 s.c om*/ 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(); } }
From source file:sce.RESTXMLJob.java
@Override public void execute(JobExecutionContext context) throws JobExecutionException { try {//from ww w . ja v a 2 s . c o m //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. *//*from www . ja v a 2 s .c om*/ 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 w w . j ava 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/*from ww w. jav a2 s. c om*/ 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.//www. j ava 2 s . co 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.uf.togathor.Togathor.java
@Override public void onCreate() { super.onCreate(); sInstance = this; mPreferences = new Preferences(this); mPreferences.clearFlagsForTutorialEachBoot(getApplicationContext().getPackageName()); gOpenFromBackground = true;/*from w ww .j a v a 2s .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(); }