How to execute a command in javascript to upload files to application? - javascript

Am working on protractor framework and I need to upload files to the application using a script.I know how to do it in java but no idea in javascript. Can someone please help me on this:
Java code :
public static void fileUpload(String script, String filePath) {
try {
Process proc = Runtime.getRuntime().exec("script " + script + " " + filePath);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
}
Thanks !

Not sure what you meant by script here. Using sendkeys with upload input element should work in protractor.
like :
var path = require('path');
var fileToUpload = '../test-resources/filetoupload'; //(the example relative path of the file )
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.css('input[type="file"]')).sendKeys(absolutePath);
uploadButton().click();

Related

How can I call a photoshop script using a java application and printting the output Javascript console

I have a springboot app that calls a .jsx script. It is a simple script, just read a JSON file and print some values on console.
My problem is when I try to get the output and log on my springboot app.
When I run the script using ExtendToolkit Script, I get the follow info on console:
Id: 6989996500
Result: undefined
But, when I run through Springboot, the output is:
Exit status: 0
Output: [TypeQuest] Timestamp=2023-02-01T05:00:19.434 ThreadId=6304 Type=TQ_WARN Component=TQFontManager Description="Not using user-specific cache directory; using: C:\Users\lnrei\AppData\Roaming\Adobe\typequest.2"
Here is my spring code:
`
try {
String[] command = {"C:\\Program Files\\Adobe\\Adobe Photoshop 2022\\Photoshop.exe",
"-r",
"C:\\Users\\lnrei\\OneDrive\\Documentos\\Projeto\\Photoshop Scripts\\scriptPSthumbnail.jsx"};
//Process process = new ProcessBuilder(command).start();
Process process = Runtime.getRuntime().exec(command);
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = reader.readLine()) != null)
output.append(line + "\n");
int exit = process.waitFor();
System.out.println("Exit status: " + exit);
System.out.println("Output: " + output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}`
As you can see, I trying to use process.getInputStream() to catch the output and sendo to a string.
Here is my .jsx file:
`
#include "json2.js";
var contentPath = "C:/Users/lnrei/OneDrive/Documentos/Projeto/content/content.json";
var contentFile = new File(contentPath);
if(contentFile.exists) {
contentFile.open("r");
var jsonStr = contentFile.read ();
contentFile.close ();
var content = JSON.parse(jsonStr);
$.writeln ("Id: " + content.matchId)
} else {
$.writeln ("Error handling the file!");
}
$.writeln();
photoshop.quit();`

Read data from a website using Nashorn

I want to retrieve data from a website using Nashorn script engine
I have the java code where I can retrieve data from a sample website template.
Now I want to call that java file from java script file.
following is the code:
JAVA CODE(Nsample.java):
package sample;
import java.net.*;
import java.io.*;
public class Nsample
{
public static void main(String[] args)
{
String output = getUrlContents("https://freewebsitetemplates.com/");
System.out.println(output);
}
public static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
JAVASCRIPT code:(sample.js)
var n = Java.type('C.JavaFolder.sample.Nsample');
var result = n.getUrlContents("https://freewebsitetemplates.com/");
print(result);
I'm trying to compile javascript code using command prompt but it is showing CLASSNOTFOUNDEXCEPTION.
The command was jjs sample.js.Im assuming I did some mistake in Java.type() function.
Can anyone solve this?
This line is the problematic line:
var n = Java.type('C.JavaFolder.sample.Nsample');
Java.type accepts fully qualified java type name. Based on your Java code, your package seems to be "sample" and class name is "Nsample". So the fully qualified class name would be "sample.Nsample".
You should compile your Java classes and specify the directory in -classpath option (of jjs tool or your java application if you use javax.script API with nashorn).
Instead of calling Java from JavaScript , I tried to call JavaScript from java and worked well.
I created some functions in JavaScript and invoked those functions from Java code.
Following is the code.Hope this helps.
Test.java:
import javax.script.*;
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws Exception{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
engine.eval(new FileReader("test.js"));
Invocable invoke = (Invocable)engine;
Object res = invoke.invokeFunction("httpGet","https://www.javaworld.com");
System.out.println(res);
}
}
test.js:
var httpGet = function(theUrl){
var con = new java.net.URL(theUrl).openConnection();
con.requestMethod = "GET";
return asResponse(con);
}
function asResponse(con){
var d = read(con.inputStream);
return d;
}
function read(inputStream){
var inReader = new java.io.BufferedReader(new
java.io.InputStreamReader(inputStream));
var inputLine;
var response = new java.lang.StringBuffer();
while ((inputLine = inReader.readLine()) != null) {
response.append(inputLine);
}
inReader.close();
return response.toString();
}

How can show document file in iframe when i get the file name from database?

How can show document file in iframe when i get the file name from database?My database table name is File and my viewmodel is MyFileModel.
public ActionResult Create(HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid)
{
db.Files.Add(new File()
{
FileName = Path.GetFileName(file.FileName)
});
db.SaveChanges();
}
}
catch (Exception)
{
var error = "Sorry not save";
}
return Content("");
}
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
FileStream fs = new FileStream(Server.MapPath(file.FileName), FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
<div id="frame">
<iframe src="#Url.Action("GetPDF","Home")" width="900px" height="500px"></iframe>
</div>
`
The answer which I am posting is all on an assumption, I do not have clear picture of your solution.
If you are not saving a physical file try to save it in a folder and then save the name in the DB OR try to save the entire path in the DB.
Method 1 :
If you are saving the file in a folder say File best way is to add a key in the web.config(.config file which is at the root) as follows
<add key="FilePath" value= "~/File/"/>
and then modify your C# code as follows
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
string fileName = file.FileName;
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs,"text/plain"); // "text/plain" if your file content-type is text file
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
Method 2 :
If you are saving the entire path then it makes coding much more simpler and you need not change the code you have written, just go ahead with the same.
Hope this would help you.
I think the way the pdf will open is dependent on the browser that the user uses.
You probably need something like: https://pdfobject.com/.
Good luck!

Call internal javascript function from java code

I have to call a javascript function named function startPolling() and created into hill.js file (/Demo MM/src/main/webapp/static/assets/js/hill.js) from java code. How can i do?Thanks
I'm using this code but receive exception
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
if (!(engine instanceof Invocable)) {
System.out.println("Invoking methods is not supported.");
return "500";
}
Invocable inv = (Invocable) engine;
String scriptPath = "/Demo MM/src/main/webapp/static/assets/js/hill.js";
try {
engine.eval("load('" + scriptPath + "')");
} catch (ScriptException e) {
return "500";
}
Make sure you are in the correct working directory to begin with. I get your code working.
To output working directory:
System.out.println("Working Directory = " +
System.getProperty("user.dir"));

Android webview, loading javascript file in assets folder

I've seen this question has been asked a lot of times, but still can't manage to get my code working.
I want my webview to load some URL (say www.google.com) and then apply some javascript stored in assets/jstest.js, which contains the following:
function test(){
document.bgColor="#00FF00"; //turns to green the background color
}
And here's where I try to load the JS:
#Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:(function() { "
+ " document.bgColor='#FF0000';" //turns to red the background color
+ " var script=document.createElement('script'); "
+ " script.setAttribute('type','text/javascript'); "
+ " script.setAttribute('src', 'file:///android_asset/jstest.js'); "
+ " script.onload = function(){ "
+ " test(); "
+ " }; "
+ " document.getElementsByTagName('head')[0].appendChild(script); "
+ "})()");
}
I know the javascript here works because the background color actually turns to red, but for some reason it won't load jstest.js. I think the problem might be in file path (I'm certain every other line of the javascript code is correct), but it looks correct to me. And the file is in the right folder.
What am I missing?
EDIT:
Since WebResourceResponse class is available only with API Level 11, here's what I've figured out in the end.
public void onPageFinished(WebView view, String url){
String jscontent = "";
try{
InputStream is = am.open("jstest.js"); //am = Activity.getAssets()
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while (( line = br.readLine()) != null) {
jscontent += line;
}
is.close();
}
catch(Exception e){}
view.loadUrl("javascript:(" + jscontent + ")()");
}
with the jstest.js simply containing:
function() {
document.bgColor="#00FF00";
}
I tried the same thing, loading a bookmarklet (the javascript code in your loadUrl() call) into a third-party page. My bookmarklet also depends on other assets (javascript and css files) which would not load with a file:///android_asset URL.
That's because the security context of the page is still that of, e.g., http://www.google.com, and that's not allowed access to file: URLs. You should be able to see the errors if you supply/override a WebChromeClient.onConsoleMessage().
I ended up with a kludge where I changed the bookmarklet's asset references to a bogus URL scheme, like:
asset:foo/bar/baz.js
and added a WebViewClient.shouldInterceptRequest() override which looks for those and loads them from assets using AssetManager.open().
One thing I don't like about this kludge is that the asset: scheme is open to any third-party HTML/Javascript on any page my view loads, giving them access to my app's assets.
One alternative, which I didn't try, would be to embed the sub-assets in the bookmarklet using data: URLs, but that can get unwieldy.
I'd much prefer it if there was a way to manipulate the security context of just the JS bookmarklet I'm loading in loadUrl(), but I can't find anything like that.
Here's a snippet:
import android.webkit.WebResourceResponse;
...
private final class FooViewClient extends WebViewClient
{
private final String bookmarklet;
private final String scheme;
private FooViewClient(String bookmarklet, String scheme)
{
this.bookmarklet = bookmarklet;
this.scheme = scheme;
}
#Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl(bookmarklet);
}
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
if (url.startsWith(scheme))
try
{
return new WebResourceResponse(url.endsWith("js") ? "text/javascript" : "text/css", "utf-8",
Foo.this.getAssets().open(url.substring(scheme.length())));
}
catch (IOException e)
{
Log.e(getClass().getSimpleName(), e.getMessage(), e);
}
return null;
}
}
I think the iceam cream webview client of cordova does the very thing you want to do.
It would be nice if this was documented somewhere but, as far as I can see, it is not.
Take a look at cordova's android github:
https://github.com/apache/incubator-cordova-android/blob/master/framework/src/org/apache/cordova/IceCreamCordovaWebViewClient.java
Here is how i ended up doing it. I used the Content:// protocol and set up a contentprovider to handle returning a file descriptor to the system
Here is my fileContentProvider:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;
public class FileContentProvider extends ContentProvider {
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) {
Log.d("FileContentProvider","fetching: " + uri);
ParcelFileDescriptor parcel = null;
String fileNameRequested = uri.getLastPathSegment();
String[] name=fileNameRequested.split("\\.");
String prefix=name[0];
String suffix=name[1];
// String path = getContext().getFilesDir().getAbsolutePath() + "/" + uri.getPath();
//String path=file:///android_asset/"+Consts.FILE_JAVASCRIPT+"
/*check if this is a javascript file*/
if(suffix.equalsIgnoreCase("js")){
InputStream is = null;
try {
is = getContext().getAssets().open("www/"+Consts.FILE_JAVASCRIPT);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File file = stream2file(is,prefix,suffix);
try {
parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
} catch (FileNotFoundException e) {
Log.e("FileContentProvider", "uri " + uri.toString(), e);
}
}
return parcel;
}
/*converts an inputstream to a temp file*/
public File stream2file (InputStream in,String prefix,String suffix) {
File tempFile = null;
try {
tempFile = File.createTempFile(prefix, suffix);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tempFile.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
IOUtils.copy(in, out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tempFile;
}
#Override
public boolean onCreate() {
return true;
}
#Override
public int delete(Uri uri, String s, String[] as) {
throw new UnsupportedOperationException("Not supported by this provider");
}
#Override
public String getType(Uri uri) {
throw new UnsupportedOperationException("Not supported by this provider");
}
#Override
public Uri insert(Uri uri, ContentValues contentvalues) {
throw new UnsupportedOperationException("Not supported by this provider");
}
#Override
public Cursor query(Uri uri, String[] as, String s, String[] as1, String s1) {
throw new UnsupportedOperationException("Not supported by this provider");
}
#Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
throw new UnsupportedOperationException("Not supported by this provider");
}
}
in the manifest i defined the provider:
<provider android:name="com.example.mypackage.FileContentProvider"
android:authorities="com.example.fileprovider"
/>
Here is the javascript o inject into the webview:
webView.loadUrl("javascript:(function() { "
+ "var script=document.createElement('script'); "
+ " script.setAttribute('type','text/javascript'); "
+ " script.setAttribute('src', 'content://com.example.fileprovider/myjavascriptfile.js'); "
/* + " script.onload = function(){ "
+ " test(); "
+ " }; "
*/ + "document.body.appendChild(script); "
+ "})();");
and here is the myjavascriptfile.js (as an example):
function changeBackground(color) {
document.body.style.backgroundColor = color;
}
Maybe you could have assets as 'html/javascript templates'. You could combine different of these text sources and string logic to compose your desired html to be loaded into the WebViewer. Then, you use .loadData instead of .loadUrl
I'm using it on my own and it seems to work pretty well.
Hope it helps!
With the following two conditions given:
minSdkVersion 21
targetSdkVersion 28
I am able to successfully load any local asset (js, png, css) via the following Java code
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Uri uri = request.getUrl();
if (uri.getHost().equals("assets")) {
try {
return new WebResourceResponse(
URLConnection.guessContentTypeFromName(uri.getPath()),
"utf-8",
MainActivity.this.getAssets().open(uri.toString().substring(15)));
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
And in the HTML code I can use
<link rel="stylesheet" href="https://assets/material.min.css">
<script src="https://assets/material.min.js"></script>
<script src="https://assets/moment-with-locales.min.js"></script>
<img src="https://assets/stackoverflow.png">
In Java the following then also works (you'd also need to add a favicon.ico to the assets)
webView.loadUrl("https://assets/example.html");
Using https:// as the scheme allows me to load local assets from a page served via HTTPS without security issues due to mixed-content.
None of these require to be set:
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);

Categories