I have java class which I'm doing file copy to another directory. I want to call it in javascript. I wrote something like this.
for(var i=0;i<arrayExtensions.length;i++){
if(arrayExtensions[i]==value.extType){
var x=new Package.org.solr.copyImages();
var y=x.main(value.FileName,value.FilePath);
document.getElementById(showImages).src=y;
$(this).find("#showImages").fadeIn();
}
else{
$(this).find("#showImages").fadeOut();
}
But when I run my project it gives me this error in console.
Uncaught ReferenceError: Package is not defined
at HTMLAnchorElement.<anonymous> (index.jsp:216)
at HTMLDocument.dispatch (jquery-1.12.4.js:5226)
at HTMLDocument.elemData.handle (jquery-1.12.4.js:4878)
My java codes like this
public static String main(String name,String path) {
// TODO Auto-generated method stub
File original=new File(path);
File dest=new File("T:\\Temp\\");
try {
FileUtils.copyFileToDirectory(original, dest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String newPath="T:\\Temp\\"+name;
return newPath;
}
What am I doing wrong?
Java doesn't run in the web browser. When using Java and JavaScript together, typically you do an ajax request to the server, which runs the Java code and produces a result, which is then sent back to the browser to be processed by the JavaScript code that did the ajax request (specifically, its success handler).
The answers to this question may also be useful: What is the difference between client-side and server-side programming?
Related
I would like to invoke or open Perspective(or Views) from JavaScript function.
I have an Eclipse RCP application, where I have embedded My HTML page. On button click from HTML page, i would like to open Eclipse RCP perspective or View.
I have tried as shown below from javascript function
function populateGeometryData(){
alert('Inside populateGeometryData() function !!!!!');
var geoMetryDataClass = Java.type("com.test.app.ui.view.PageView");
geoMetryDataClass.populateGemetryData("TestVal");
}
Where PageView is one of my perspective. But I got " Uncaught ReferenceError: Java is not defined" .
I think, this error is because of Chrome no longer supports NPAPI (technology required for Java applets). So, is there any other ways to invoke Java class method from JavaScript?
Below is how, I am launching my HTML page from Eclipse RCP code.
#Override
public void createPartControl(Composite parent) {
String user = ExecuteRestService.getLoggedInUser();
System.out.println("Login User "+user);
String html = "/Pages/index.html";
Bundle appBundle = FrameworkUtil.getBundle(this.getClass());
if(appBundle == null) {
System.out.println("bundle is null");
return;
}
URL url = FileLocator.find(appBundle, new Path(html), null);
try {
url = FileLocator.toFileURL(url);
} catch (IOException e) {
// TODO Auto-generated catch block#*
e.printStackTrace();
}
Browser browser = new Browser(parent, SWT.None);
String urlVal = url.toString()+"?LoginUser="+user;
browser.setUrl(urlVal);
}
I am looking some suggestions to call Java Class Method or to Invoke Eclipse RCP perspective from JavaScript function.
Thank you in advance.
UPDATE
As Greg suggested in comments section, using "BrowserFunction" we can call Java class method in Eclipse RCP from javascript if you are using SWT browser to launch your HTML page.
new BrowserFunction(browser, "populateGeometricData")
{
#Override
public Object function(Object[] objects)
{
if(objects.length == 0) {
System.out.println(" array is zero");
}else {
System.out.println("Call from Javascript"
+ objects.length);
System.out.println("Request Id "+ objects[0]);
}
return null;
}
};
I am making some java project about non-using browser service.
So, I want to use some JavaScript function from server (which is a callback from my POST)
I saw many codes about using JavaScript in java, but it's from local files.
I think one solution about this:
When callback is coming, save this code and use it again. But I think it's not optimal for our project.
Can you give me any other solution?
Thank you in advance.
Yes, you can, as #Daniel Baranowski suggested above.
And no, you absolutely shouldn't.
Running any code submitted by the client is putting yourself in an extreme risk.
Can it access your filesystem? Then you're in trouble.
Can it execute network calls? Then you're also in trouble.
And even if you blocked those options, do you check that this user code terminates in time?
It is certainly possible but it can expose you to huge security risks.
Nothing is stopping you from running JavaScript code directly from a String. Having it saved in a file is not a requirement. You can get the body of the POST which was send do your server and execute it somewhat like this:
package example;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Example {
private final ThreadLocal<NashornScriptEngine> engineHolder;
public Example() {
// You don't need to run code from files. The code can be a string which was posted to your server.
String jsCodeToRun = "function helloWorld(name) { return { value: 'Hello' + name } }"
this.engineHolder = ThreadLocal.withInitial(() -> {
NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
try {
nashornScriptEngine.eval(jsCodeToRun);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return nashornScriptEngine;
});
}
public JSObject runTheCode(String name) {
try {
JSObject result = (JSObject) engineHolder.get().invokeFunction("helloWorld", name);
// The result will be an object returned by our helloWorld function.
return result;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
Windows won't let my WebView_ScriptNotify Event receive a call if the html is loaded from ms-appdata.
I'm aware that I can use the ms-appx-web protocol to load such a file from my app bundle, but this is no option because the data to show are downloaded after install of the app.
I also can't just use webView.navigateToString because this won't include the referenced libraries in the html file.
Currently I'm trying something like this in my Class.xaml.cs
WebView webView = new WebView();
webView.ScriptNotify += WebView_ScriptNotify;
Uri navigationUri = new Uri(#"ms-appdata:///local/index.html");
webView.Navigate(navigationUri);
and
private void WebView_ScriptNotify(object sender, NotifyEventArgs e)
{
System.Diagnostics.Debug.WriteLine("ScriptNotifyValue: " + e.Value);
//I want to do the magic here, but this will never be called
}
in the html file is
<div id="content">
<div class="btn" onClick="window.external.notify('hello world');"</div>
</div>
Furthermore, it's no option to use InvokeScript(), because I don't know when the event must be fired and the values for it.
Yet it's mandatory to use files from ms-appdata.
Do you know a solution for this?
Even an alternative workaroung would amaze me.
Ref Script notify changes in XAML:
For content to be able to send notifications the following conditions apply:
The source of the page should be from the local system via NavigateToString(), NavigateToStream() or ms-appx-web:///
Or
The source of the page is delivered via https:// and the site domain name is listed in the app content URI’s section of the package manifest.
So to solve this issue, we can use WebView.NavigateToLocalStreamUri method with the protocol ms-local-stream://, rather than ms-appdata://. For example:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// The 'Host' part of the URI for the ms-local-stream protocol needs to be a combination of the package name
// and an application-defined key, which identifies the specific resolver, in this case 'MyTag'.
Uri url = webView.BuildLocalStreamUri("MyTag", "index.html");
StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
// Pass the resolver object to the navigate call.
webView.NavigateToLocalStreamUri(url, myResolver);
}
private void webView_ScriptNotify(object sender, NotifyEventArgs e)
{
System.Diagnostics.Debug.WriteLine("ScriptNotifyValue: " + e.Value);
}
}
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
// Because of the signature of the this method, it can't use await, so we
// call into a seperate helper method that can use the C# await pattern.
return GetContent(path).AsAsyncOperation();
}
private async Task<IInputStream> GetContent(string path)
{
// We use app's local folder as the source
try
{
Uri localUri = new Uri("ms-appdata:///local" + path);
StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream;
}
catch (Exception) { throw new Exception("Invalid path"); }
}
}
For more info, please see Remarks and Examples in WebView.NavigateToLocalStreamUri method and also Custom URI resolving in What’s new in WebView in Windows 8.1. Besides, there is also a WebView control (XAML) sample on GitHub.
I had implemented HttpHandler for Js extension for google api hosted jquery script files. because when it is called need to replace http with https. But visual studio started compiling javascript on pages being loaded. how do I suppress this behavior. And most interesting why did it happened.
My Http Handler :
public class HttpToHttpsHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
try
{
if (context.Request.RawUrl.Contains("http:"))
{
context.Response.ContentType = "text/plain";
string newUrl = context.Request.RawUrl.Replace("http", "https");
context.Server.Transfer(newUrl);
}
}
catch (Exception)
{
throw;
}
}
}
What possibly went wrong.
It is because you have used Server.Transfer() which doesn't issue redirect to the browser but changes the execution path on the server - in the result ASP.NET will try to create something out of your JavaScript.
You want to make a simple redirection so just use Response.Redirect()
context.Response.Redirect(newUrl, false);
Also I would like suggest a more safe approach for altering the URL (in case there would be port number in URL etc.):
if (!context.Request.IsSecureConnection)
{
UriBuilder secureUriBBuilder = new UriBuilder(context.Request.Url);
secureUriBBuilder.Scheme = Uri.UriSchemeHttps;
//Ude default port for schema - alter this if your server is using custom port for HTTPS
secureUriBBuilder.Port = -1;
context.Response.Redirect(secureUriBBuilder.Uri.ToString(), false);
}
Also remember that the entire page will remain in non-safe mode if you will load the HTML in HTTP and try to load only JavaScript through HTTPS - you should consider redirection in Global.asax or usage of URL Rewrite module.
I have a report in BIRT that has non-trivial JavaScript (scripted data source). The JavaScript is all a bit wobbly, and suspect to regress. For that reason and others I have written a JUnit test that populates the data, runs the report (createRunAndRenderTask and run that task) and do some validation on the resulting report.
Obviously this test will fail when the BIRT engine throws any exceptions. However, upon JavaScript errors in the report, no exceptions are thrown. And that does not feel good. Can I change this somehow to have the BIRT engine throw exceptions upon JavaScript errors?
I tried this by having a host of JavaScript errors during development of the report. Think of typos in the scripted data source. They are spit out in the console, but no exceptions.
E.g.:
<method name="open"><![CDATA[count = 0;
this should break]]></method>
This shows in the console:
... Fail to execute script in function __bm_OPEN(). Source:
------
" + count = 0;
this should break + "
-----
A BIRT exception occurred. See next exception for more information.
ReferenceError: "this should break" is not defined. (/report/data-sets/script-data-set[#id="9"]/method[#name="open"]#3)
Thank you for your suggestions!
I ended up doing this and pretty okay with it:
IRunAndRenderTask task = ...
...
task.setErrorHandlingOption(IEngineTask.CANCEL_ON_ERROR);
...
task.run();
evaluateStatus(task, reportName);
task.close();
And:
private void evaluateStatus(IRunAndRenderTask task, String reportName) {
if (task.getStatus() == IEngineTask.STATUS_CANCELLED) {
String message = "report failed: " + reportName;
List<Throwable> errors = task.getErrors();
if (!errors.isEmpty()) {
throw new RuntimeException(message, errors.get(errors.size() - 1));
}
throw new RuntimeException(message);
}
}
Depending on javascript errors, the BIRT engine will catch them and still try to display the report.
I think you could override this by wrapping your javascript code (Rhino script) in a try...catch expression, and explicitely throw a BirtException if something wrong happens:
try{
//your javascript stuff
var test=null;
test.toString();
}catch(e){
var exception=new org.eclipse.birt.core.exception.BirtException("Custom exception:"+e);
throw exception;
}