I would like to ask if someone has tried to change the default download location on Microsoft Edge Chromium driver using selenium 3.X.
On Chrome browser, we could use something like this
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", savePAth);
chromePrefs.put("prompt_for_download", false);
options.setExperimentalOption("prefs", chromePrefs);
Info:
Microsoft Edge Browser version: 80.0.361.66 (Official build) (64-bit)
Thanks in Advance
Try using the following setup (Java Bindings):
public WebDriver newDriver() {
try {
EnvironmentVariables vars = SystemEnvironmentVariables.createEnvironmentVariables();
String version = vars.getProperty("webdriver.edgedriver.version");
WebDriverManager.edgedriver().version(version).setup();
EdgeOptions options = new EdgeOptions();
EdgeDriverService edgeDriverService = EdgeDriverService.createDefaultService();
EdgeDriver edgeDriver = new EdgeDriver(edgeDriverService, options);
final String downloadPath = ${your path}
//************* Enable downloading files / set path *******************
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", downloadPath);
commandParams.put("params", params);
ObjectMapper objectMapper = new ObjectMapper();
HttpClient httpClient = HttpClientBuilder.create().build();
String command = objectMapper.writeValueAsString(commandParams);
String u = edgeDriverService.getUrl().toString() + "/session/" + edgeDriver.getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "application/json");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
return edgeDriver;
} catch (Exception e) {
throw new Error(e);
}
}
I was able to download files to the desired path using this snippet. Source here
Related
1.send byte array from java and convert base64 in javascript
==java code(spring)==
public ResponseEntity<byte[]> download(String key) throws IOException {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKeyId, secretKeyId);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(clientRegion).build();
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
S3Object s3Object = s3Client.getObject(getObjectRequest);
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);
String fileName = URLEncoder.encode(key, "UTF-8").replaceAll("\\+", "%20");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentLength(bytes.length);
httpHeaders.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
}
↑ aws image download code
#RequestMapping(value = "/api/image/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> imageDownload(String key) throws IOException {
ResponseEntity<byte[]> byteStream = awsS3.download(key);
return byteStream;
}
}
↑ return image byte array
==javascript code(react)==
const result = await GetAPI("/api/image/download?key=housing/userid/1626770531982_1536568681_3.jpg");
console.log('result',result);
const array = new Uint32Array(Buffer.from(result.data,"binary"));
console.log('window.btoa(array)',window.btoa(array));
↑ convert byte array to base64
↑ convert byte array to base64 result captured image
============================================================================
2. send base64 from java and check in javascript
#RequestMapping(value = "/api/image/download", method = RequestMethod.GET)
public String imageDownload(String key) throws IOException {
ResponseEntity<byte[]> byteStream = awsS3.download(key); byte[]
encodedByteStream = com.amazonaws.util.Base64.encode(byteStream.getBody());
String base64DataString = new String(encodedByteStream, "UTF-8");
return base64DataString;
}
↑ send base64 to javascript
↑ send base64 to javascript captured image
question : why is it different the value of converted in java then send to javascript and the value of sending to javascript from java then convered in javascript?
sorry my english.
You are using an old Java API for this use case. To get an object in an Amazon S3 bucket as bytes, you should consider using the AWS SDK for Java V2.
Here is Amazon S3 Java V2 code that uses the s3.getObjectAsBytes method to get an object as a byte[].
private S3Client getClient() {
// Create the S3Client object
Region region = Region.US_WEST_2;
S3Client s3 = S3Client.builder()
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.region(region)
.build();
return s3;
}
public byte[] getObjectBytes (String bucketName, String keyName) {
s3 = getClient();
try {
// Create a GetObjectRequest instance
GetObjectRequest objectRequest = GetObjectRequest
.builder()
.key(keyName)
.bucket(bucketName)
.build();
// Get the byte[] from this S3 object
ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
byte[] data = objectBytes.asByteArray();
return data;
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
Replace your V1 code with this V2 code and then use Java encoding logic.
If you are not familiar with working with AWS SDK for Java V2, I recommend starting here:
https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
My file resides on some location on my machine say C://users//abc.txt and i want to write a java program to transfer this file using REST API over HTTP. I used MockHttpServelet Request to create the request, but somehow i am unable to transfer the file
Use HttpClient:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
With Authentication:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
String username = "username"; // Replace with your username
String password = "password"; // Replace with your password
RequestConfig requestConfig =
RequestConfig.custom().
setAuthenticationEnable(true).
build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredential(username, password));
CloseableHttpClient httpClient =
HttpClients.custom().
setDefaultRequestConfig(requestConfig).
setDefaultCredentialsProvider(credentialsProvider).
build();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
String location="C:\\Usersabc.img";
Path path = Paths.get(location);
String name=location.substring(location.lastIndexOf("\\")+1);
MultipartEntity multipart= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
multipart.addPart("image", new ByteArrayBody(Files.readAllBytes(path), ContentType.APPLICATION_OCTET_STREAM.getMimeType(),name));
}
catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
I have configured Spring data solr 1.5.4 to use Apache Solr 5.2.1 and this is my configuration:
#Bean
public SolrTemplate solrTemplate() {
return new SolrTemplate(solrServerFactory());
}
#Bean
public SolrServerFactory solrServerFactory() {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
return new HttpSolrServerFactory(solrServer(), "", credentials, "BASIC");
}
#Bean
public SolrServer solrServer() {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);
params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, username);
params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, password);
params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345);
params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true);
params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345);
params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345);
params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345);
params.set(HttpClientUtil.PROP_USE_RETRY, false);
HttpClient httpClient = HttpClientUtil.createClient(params);
HttpSolrServer httpSolrServer = new HttpSolrServer("http://" + host + ":" + port + "/solr/", httpClient);
return httpSolrServer;
}
but when I want to save the document, this exception occurs:
14:28:45,863 Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
14:28:45,863 at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:660)
14:28:45,863 at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
14:28:45,863 at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
Please help me.
Until this is fixed, implement PreemptiveAuthInterceptor and addRequestInterceptor before createClient
Sample is available at PreemptiveAuthInterceptor.java
e.g.
ModifiableSolrParams params = new ModifiableSolrParams();
params.add(HttpClientUtil.PROP_BASIC_AUTH_USER, uname);
params.add(HttpClientUtil.PROP_BASIC_AUTH_PASS, pwd);
params.add(HttpClientUtil.PROP_BASIC_AUTH_PASS, pwd);
HttpClientUtil.addRequestInterceptor(new PreemptiveAuthInterceptor());
CloseableHttpClient httpclient = HttpClientUtil.createClient(params);
I need help with sending email w/attachment using Gmail Api in c#.
I have read Google website on sending emails with attachment but the example is in java.
Its too late for the answer, but posting it in case anyone needs it:)
Need MimeKit library for this: can be installed from NuGet.
Code:
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("fromemailaddress#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("toemailaddress.com.au"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scope,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
}
Scope can be:
GmailSend or GmailModify
static string[] Scope = { GmailService.Scope.GmailSend };
static string[] Scope = { GmailService.Scope.GmailModify };
Base64UrlEncode function:
private string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
I have an example in VB.net. GMail API Emails Bouncing.
Google page provides examples in Java and Python only. The objects being used in the Java example are not available in .Net version of API. It is not possible to translate those examples.
Fortunately, it is quite easy to do the same in C#/VB. Just use plain old Net.Mail.MailMessage to create a message including attachments, then use MimeKit (NuGet it) to convert the message into string and pass the string (after encoding Base64) to "Raw" field of message.send of Gmail API.
There's nothing particular to sending an attachment with the Gmail API. Either way the Gmail API message.send() takes a full RFC822 email message in the message.raw field (urlsafe base64 encoded). The main trick is building up such an RFC822 email message string in your language. I imagine there are some MIME message librarys in C# and that's the main issue is finding those libraries. I don't do C# but javax.internet.mail.MimeMessage works well in java and the 'email' module is good for python.
This other post seems relevant:
How to send multi-part MIME messages in c#?
string[] Scopes = { GmailService.Scope.GmailSend };
string ApplicationName = "Gmail API App";
public GmailForm()
{
InitializeComponent();
SendHTMLmessage();
}
string Base64UrlEncode(string input)
{
var data = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(data).Replace("+", "-").Replace("/", "_").Replace("=", "");
}
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("youremail#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\attachment.pdf";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("receiver#mail.com"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,Scopes,"user",CancellationToken.None,new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
are there any good examples on how to use Google App Engine from Silverlight, preferably without writing custom webservices?
Cheers
Nik
Here is my approach based heavily on Scott Seely's post
Simply passes XML around, .xap is also served by GAE. I only just got this working yesterday so it is still work in progress.
Google:
app.yaml
application: wowbosscards
version: 1
runtime: python
api_version: 1
handlers:
- url: /WowBossCards.html
static_files: WowBossCards.html
upload: WowBossCards.html
mime_type: text/html
- url: /clientaccesspolicy.xml
static_files: clientaccesspolicy.xml
upload: clientaccesspolicy.xml
mime_type: text/xml
- url: /WowBossCards.xap
static_files: WowBossCards.xap
upload: WowBossCards.xap
mime_type: application/x-silverlight-app
- url: .*
script: wowbosscards.py
wowbosscards.py
#!/usr/bin/env python
import cgi
import datetime
import wsgiref.handlers
import os
import logging
import string
import urllib
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class Xml(db.Model):
xmlContent = db.TextProperty()
date = db.DateTimeProperty(auto_now_add=True)
class XmlCrud(webapp.RequestHandler):
def get(self, xmlType):
xmlKey = string.capitalize(xmlType)
xml = Xml.get_by_key_name(xmlKey)
self.response.headers['Content-Type'] = "application/xml"
self.response.out.write(xml.xmlContent)
def post(self, xmlType):
logging.debug("XmlCrud POST")
xmlKey = string.capitalize(xmlType)
xml = Xml.get_by_key_name(xmlKey)
if len(self.request.get('content')) > 0 :
xml.xmlContent = self.request.get('content')
else:
xml.xmlContent = self.request.body
xml.put()
self.redirect('/upload/' + xmlType)
def main():
Xml.get_or_insert("Bosses", xmlContent="<a>Bosses go here</a>")
Xml.get_or_insert("Dungeons", xmlContent="<a>Dungeons go here</a>")
application = webapp.WSGIApplication([
(r'/xml/(.*)', XmlCrud),
], debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Silverlight:
private class RequestExtended
{
public VoidCall CallBack;
public WebRequest Request;
public Uri Host;
public RequestExtended(WebRequest request, VoidCall callBack, Uri host)
{
Request = request;
CallBack = callBack;
Host = host;
}
}
public static void ImportFromGoogle(Uri host, VoidCall callBack)
{
try
{
if (host.Host == "localhost")
{
host = new Uri(host.Scheme + #"://" + host.Host + ":8080");
}
var bossesCrud = new Uri(host, "/xml/bosses");
var bossesRequest = WebRequest.Create(bossesCrud);
bossesRequest.BeginGetResponse(BossesResponse, new RequestExtended(bossesRequest, callBack, host));
}
catch (Exception ex)
{
}
}
public static void BossesResponse(IAsyncResult result)
{
var requestExtended = result.AsyncState as RequestExtended;
try
{
WebResponse response = requestExtended.Request.EndGetResponse(result);
Stream responseStream = response.GetResponseStream();
byte[] bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, bytes.Length);
responseStream.Close();
var enc = new System.Text.UTF8Encoding();
string xml = enc.GetString(bytes, 0, bytes.Length);
bosses = GetCollectionFromXmlString<BossCollection>(xml);
if (requestExtended.CallBack != null) requestExtended.CallBack();
}
catch (WebException we)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
response.Close();
}
catch (Exception e)
{
}
}
public static void SaveBossesToGoogle(Uri host)
{
if (host.Host == "localhost")
{
host = new Uri(host.Scheme + #"://" + host.Host + ":8080");
}
var bossesCrud = new Uri(host, "/xml/bosses");
var request = WebRequest.Create(bossesCrud);
request.Method = "POST";
request.ContentType = "text/xml"; //"application/x-www-form-urlencoded";
request.BeginGetRequestStream(GetSaveBossesRequestStreamCallback, new RequestExtended(request, null, host));
}
static void GetSaveBossesRequestStreamCallback(IAsyncResult result)
{
var requestExtended = result.AsyncState as RequestExtended;
try
{
Stream stream = requestExtended.Request.EndGetRequestStream(result);
var xmlSerializer = new XmlSerializer(typeof(BossCollection));
var xmlText = new StringBuilder();
using (TextWriter textWriter = new StringWriter(xmlText))
{
xmlSerializer.Serialize(textWriter, Store.Bosses);
textWriter.Close();
}
var enc = new System.Text.UTF8Encoding();
var bytes = enc.GetBytes(xmlText.ToString());
stream.Write(bytes, 0, bytes.Length);
stream.Close();
requestExtended.Request.BeginGetResponse(SaveResponse, requestExtended);
}
catch (WebException we)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
response.Close();
}
}
static void SaveResponse(IAsyncResult result)
{
var requestExtended = result.AsyncState as RequestExtended;
try
{
WebResponse response = requestExtended.Request.EndGetResponse(result);
if (requestExtended.CallBack != null) requestExtended.CallBack();
}
catch (WebException we)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
response.Close();
}
}
I'm thinking about doing the same thing, but I've not come across anything yet.
I'm thinking about using JSON.net for the comms, so basically writing a REST service in GAE for the client to call, and maybe OAuth.NET for the authentication (unless I can find the .NET port of the google one, I've not looked yet)
Silverlight is basically just .NET, tho a lite version of it, so if you can find .NET code to do something, it should work, atleast somewhat, in SL :)
But thats as far as I've got - thinking about it. Sorry, can't be of more help yet!
I'm looking at this also. There are several REST projects for GAE, I haven't tried any of them out yet, but hope to in the next week or so.
http://code.google.com/p/app3/
http://code.google.com/p/gae-json-rest/
http://code.google.com/p/appengine-rest-server/
I couldn't find any examples getting Silverlight to work with google app's Java SDK, so here is my post.
Download the demo for Expression Blend. Check the included tutorial which shows how to create a gorgeous Silverlight interface in GUI mode and integrate it with the Bing search web service. Manipulating this example into a Google example should be trivial. Good luck! :)