android studio inputStream form URL problem - java

I'm using this code for bypass the css from WebView loading , I used asset folder for loading my own css but now I need to load my custom css from URL because I need to Change my Css every week .
probelm is : after change InputStream to URL my css bypass is note working !!
My old code is :
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
and My New code is : > but is not working
private void injectCSS() {
try {
final InputStream inputStream = new URL("https://sitemname.ir/app/style.css").openStream();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}

Related

How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?

How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?
I have found the solution to the question of How to access the PDF file having blob protocol, java.net.MalformedURLException: unknown protocol: blob how to resolve in selenium java?
First convert the PDF on blob link into base64 using this code:
private String getBytesBase64FromBlobURI(ChromeDriver driver, String uri) {
String script = " "
+ "var uri = arguments[0];"
+ "var callback = arguments[1];"
+ "var toBase64 = function(buffer){for(var r,n=new Uint8Array(buffer),t=n.length,a=new Uint8Array(4*Math.ceil(t/3)),i=new Uint8Array(64),o=0,c=0;64>c;++c)i[c]='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charCodeAt(c);for(c=0;t-t%3>c;c+=3,o+=4)r=n[c]<<16|n[c+1]<<8|n[c+2],a[o]=i[r>>18],a[o+1]=i[r>>12&63],a[o+2]=i[r>>6&63],a[o+3]=i[63&r];return t%3===1?(r=n[t-1],a[o]=i[r>>2],a[o+1]=i[r<<4&63],a[o+2]=61,a[o+3]=61):t%3===2&&(r=(n[t-2]<<8)+n[t-1],a[o]=i[r>>10],a[o+1]=i[r>>4&63],a[o+2]=i[r<<2&63],a[o+3]=61),new TextDecoder('ascii').decode(a)};"
+ "var xhr = new XMLHttpRequest();"
+ "xhr.responseType = 'arraybuffer';"
+ "xhr.onload = function(){ callback(toBase64(xhr.response)) };"
+ "xhr.onerror = function(){ callback(xhr.status) };"
+ "xhr.open('GET','"+ uri +"');"
+ "xhr.send();";
String result = (String) driver.executeAsyncScript(script, uri);
return result;
}
The Second step now converts the base64 into a pdf file
public void savePDF(String path, String x){
File file = new File(path);//"D:\\dealer-portal-v2-automation\\test.pdf");
//Converting base64 to PDF
try (FileOutputStream fos = new FileOutputStream(file); ) {
// To be short I use a corrupted PDF string, so make sure to use a valid one if you want to preview the PDF file
byte[] decoder = Base64.getDecoder().decode(x);
fos.write(decoder);
System.out.println("PDF File Saved");
} catch (Exception e) {
e.printStackTrace();
}
}
Now main class
public void main(Strings[] args) {
//here pass your driver and the url
String x = getBytesBase64FromBlobURI((ChromeDriver) driver,url);
//here convert your base64 to file and sendt base64 string and the path where you want to //store your PDF
savePDF(path, x);
}

How to convert OutputStream to String in Java (Android)?

I am trying to read the string that I get inside an outputStream that in turn is written there by a ftp - from a ftp server.
I'm stuck at this problem for about 2 hours and I find it hard to belive that it's so difficult to solve.
Is there any nice solution for my problem?
Here's the relevant code:
boolean success = false;
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName));
success = ftp.retrieveFile("/ViatorAndroid/" + fileName, outputStream);
} catch (Exception e) {
Log.d("FTPDownloadLatestVersion", "e = " + e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
}
outputStream.close();
if (success) {
String versionNumberString = outputStream.getString(); // ??? I need here a way to get the string inside this output stream. Any clue how???
int versionNumber = Integer.parseInt(versionNumberString);
Log.d("FTPGetLastestVersionCode", "VersionNumber = " + versionNumber);
return BuildConfig.VERSION_CODE < versionNumber;
}
If you just want the content in a string, you build a ByteArrayOutputStream that will collect all the bytes written to it, and then turn this into a String.
Something like
try (ByteArrayOutputStream baos=new ByteArrayOutputStream()){
boolean success = ftp.retrieveFile("/ViatorAndroid/" + fileName, baos);
if (success){
String versionNumberString = new String(baos.toByteArray(),StandardCharsets.UTF_8);
...
}
}

Send a String from Android to a Spring server

I am trying to send an String from my android app to the server. The String contains: username, password and a image encoded in base 64. Between them is a space(" "). I am using heroku to store the server and I use a postgreSQL database. I have a table named users with the columns : userid,password, encoded image, all of them in format text.
When I create a new user I give the userid and the password, the column encodedimage is empty. I want to make an update to the table when I want to upload the image to the server and edit the encodedimage column.
Here is how I send the String from android:
request=Utils.name+" "+Utils.password;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
request = request+ " " + Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream outputStream = urlConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(request);
bufferedWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
outputStream.close();
int response=urlConnection.getResponseCode();
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If I update my table from cmd it works but from code it doesn't.
Here is my controller:
#Controller
public class UploadController implements Constant {
#RequestMapping(value = "/upload-image", method = RequestMethod.POST)
public void handleUploadImageRequest(#RequestBody String request) {
String[] details = request.split(" ");
String name = details[0];
String password = details[1];
byte[] decodedImage = Base64.getDecoder().decode(details[2]);
if (decodedImage.length > 0) {
try {
Image image = ImageIO.read(new ByteArrayInputStream(decodedImage));
Connection connection = null;
Statement statement = null;
String updateUSER = "UPDATE " + TABLE_USERS + " SET " + COLUMN_ENCODEDIMAGE + "='" + details[2]
+ "' WHERE " + COLUMN_USERID + "='" + name + "' AND '" + COLUMN_PASSWORD + "='" + password + "';";
try {
connection = DatabaseUtils.getConnection();
statement = connection.createStatement();
statement.executeUpdate(updateUSER);
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In heroku logs I found:
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void com.rares.controllers.UploadController.handleUploadImageRequest(java.lang.String)
Is the android code ok? Where is the problem or how should I do it. Please don't point me to deprecated methods.
I
Wrong posting. Your request should more look like:
request = "username=" + userName
+ "&password=" + passWord
+ "&image=" + base64String.
And then the values should be url encoded yet.

How do I download a file that is embedded in a web site?

At this moment I can only download files that has this type of format:
https://jdbc.postgresql.org/download/postgresql-8.1-415.jdbc2.jar
But how do I download files that aren't visible in the url file?
For e.g Skype's url path:
http://www.skype.com/sv/download-skype/skype-for-mac/downloading/
As you guys can see, there is no way I can download the file using
filePath.subString(filePath.lastIndexOf("/") + 1);
So are there other ways to do this? I did find the file embedded in the page using FireBug which is
http://www.skype.com/go/getskype-macosx.dmg
My question is, can I programmatically go through the page and get access to this file?
Here is the code which works fine for downloading
public static void fileDownload(String urlFile) throws IOException {
URL url = new URL(urlFile);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
String contentType = httpURLConnection.getContentType();
int contentLength = httpURLConnection.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
fileName = urlFile.substring(urlFile.lastIndexOf("/") + 1, urlFile.length());
}
System.out.println("Content-type= " + contentType);
System.out.println("Disposition= " + disposition);
System.out.println("Content-length= " + contentLength);
System.out.println("File name= " + fileName);
InputStream inputStream = httpURLConnection.getInputStream();
String saveFilePath = getDesiredPath() + File.separator + fileName;
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath);
int byteRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((byteRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileOutputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied httpCode=" + responseCode);
}
httpURLConnection.disconnect();
}
It's my first time working with file management and this code is actually taken from here.
You can download the file if the file download link is embedded in the page.
Something like this in the web page html:
. . .
Download Skype
. . .
For downloading the page and scanning it for links you may use JSoup
Code may look something like this:
Document doc = Jsoup.connect("http://example.com/").get();
Elements anchors = doc.select("a");
// Untested code
for (var anchor of anchors) // ECMA 6 (i think)
{
if (anchor.href.endsWith(".exe")
{
// if href is not full url i.e. not starting with http://
var downloadLink = url + anchor.href;
// Download the file with the about url
}
}

Delete amazon s3 object by versionId using rest API

I am trying to delete amazon s3 object using rest API but not getting any success. I have created the URL(signed url) at server side using java and then made XHR request to that URL at client side(i.e. from browser).
Java code that i have used to sign the url:
public static String getSignedURL(String fileName, int fileOwnerId, String versionId){
Date expiration = new Date();
long milliSeconds = expiration.getTime();
milliSeconds += 1000 * 60 * 10; // Add 10 minutes.
long seconds = (milliSeconds)/1000L;
String URL = null;
try {
String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
String canonicalizedResource = "/"+AWS_BUCKET_NAME+"/" + fileOwnerId + "/" + encodedFileName;
String stringToSign = "DELETE\n\n\n" + seconds + "\n" + canonicalizedResource +"?versionId="+versionId;
byte[] keyBytes = AWS_SECRET_API_KEY.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(stringToSign.getBytes());
byte[] base64bytes = Base64.encodeBase64(digest);
String signedString = new String(base64bytes, "UTF-8");
String signature = URLEncoder.encode(signedString, "UTF-8");
URL = "https://"+AWS_BUCKET_NAME+".s3.amazonaws.com/" + fileOwnerId +
"/" + encodedFileName +"?versionId="+versionId +"&Expires=" + seconds+"&AWSAccessKeyId=" +
AWS_ACCESS_KEY + "&Signature=" + signature;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException nsae) {
} catch (InvalidKeyException ike) {
}
System.out.println("URL IS :"+URL);
return URL;
}
And at client side:
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", deleteComplete, false);
xhr.open('DELETE', URL_GENERATED_FROM_SERVER, true);
xhr.setRequestHeader ("Access-Control-Allow-Origin", "*");
xhr.send();
Using this code for downloading an object from amazon s3 bucket works fine by replacing 'DELETE' request with 'GET'. But delete is not working. I have searched a lot but there is very less help available for rest API.
Finally, i integrated the aws sdk to delete the object from amazon s3 bucket and it works like lightning. But unable to get help doing it with rest API. So now i have used rest API for uploading and downloading and the sdk for deleting an object.

Categories

Resources