Get the local file path through actionscript (or Javascript) - javascript

I have a scenario where the user clicks on a menu item in a flex application, that menu item is supposed to give them the file browser on their OS (Mac OSX for now) and then once they choose the file, I pass that file's local path along to another part of the application (that's already written) which makes a connection using that.
I've done some research and found code that can only be used if I include the AIR SDK which I prefer not to, is there a way to do this in actionscript or javascript (since I can call javascript from my actionscript application)?
Edit: the service I am passing the path to requires having the full local path which means that after browsing files, I have to get the local path to pass it along!

Without using AIR, you can still spawn a file browse dialog for uploading local files using the FileReference class with a Flex or pure ActionScript project.
This can be abstracted to a service class.
Application
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<fx:Script>
<![CDATA[
protected function buttonClickHandler(event:MouseEvent):void
{
var uploadService:UploadService = new UploadService("http://destination.com");
uploadService.browse();
}
]]>
</fx:Script>
<s:Button label="Upload..."
click="buttonClickHandler(event)" />
</s:Application>
Upload Service
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLRequest;
public class UploadService extends EventDispatcher
{
public var fileReference:FileReference;
public var fileTypes:FileFilter;
public var uri:String
public function UploadService(uri:String)
{
this.uri = uri;
}
public function browse():void
{
fileTypes = new FileFilter("* (*.*)", "*.*;");
var allTypes:Array = new Array(fileTypes);
fileReference = new FileReference();
fileReference.addEventListener(Event.SELECT, fileSelectHandler);
fileReference.addEventListener(Event.OPEN, fileOpenHandler);
fileReference.addEventListener(Event.COMPLETE, fileCompleteHandler);
fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fileSecurityErrorHandler);
fileReference.addEventListener(IOErrorEvent.IO_ERROR, fileIoErrorHandler);
fileReference.browse(allTypes);
}
protected function fileSelectHandler(event:Event):void
{
fileReference.upload(new URLRequest(uri));
}
protected function fileOpenHandler(event:Event):void
{
dispatchEvent(new Event(Event.OPEN));
}
protected function fileCompleteHandler(event:Event):void
{
fileReference.removeEventListener(Event.SELECT, fileSelectHandler);
fileReference.removeEventListener(Event.OPEN, fileOpenHandler);
fileReference.removeEventListener(Event.COMPLETE, fileCompleteHandler);
fileReference.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, fileSecurityErrorHandler);
fileReference.removeEventListener(IOErrorEvent.IO_ERROR, fileIoErrorHandler);
dispatchEvent(new Event(Event.COMPLETE));
}
protected function fileSecurityErrorHandler(event:SecurityErrorEvent):void
{
dispatchEvent(new SecurityErrorEvent(SecurityErrorEvent.SECURITY_ERROR));
}
protected function fileIoErrorHandler(event:IOErrorEvent):void
{
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
}
}
}

Related

Applet class is not loading in a JSP

I'm working on maven web application with JSP and Servlets. I have a href which has a applet class call which loads my applet success fully from certain Servlet but on my windows only. Now I want to load this into client browser wherever this link is clicked from remote machine's IP. Please help me on this it should be loaded on client browser from HTML or JSP.
This is my class in my Java:
package com.enidiris.util;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class AppletIris extends JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean inAnApplet = true;
public AppletIris() {
this(true);
}
public AppletIris(boolean inAnApplet) {
this.inAnApplet = inAnApplet;
if (inAnApplet) {
getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
}
}
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void createGUI() {
MainPanel mainPanel = new MainPanel();
getContentPane().add(mainPanel);
}
}
This is my HTML in same web application but nothing says in console of browsers, not even loading applet.
webapp/ register.jsp
<body onload="checkSession();">
<jsp:plugin type="applet" name="AppletIris" code="com.enidiris.util.AppletIris" width="950" height="650" hspace="0" vspace="0" codebase="." >
</jsp:plugin>
<!-- <object codetype="application/java" classid="java:AppletIris.class" -->
<!-- archive="enidiris-applet.jar" width="740" height="400"></object> -->
</body>

SignalR 2.3 cannot read property client

Good day,
Unfortunately, I can not get SignalR to work for a private 1 on 1 chat.
Here the following things that I have done:
References that are situated in the head tag of my layout page in the right order:
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.3.0.js"></script>
Even added both bellow to check if either worked but no luck.
<script src="/signalr/hubs"></script>
<script src="http://localhost:50581/signalr/hubs"></script>
Have an Owin startup class:
[assembly: OwinStartup(typeof(Startup))]
namespace WebApplication6
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration();
config.EnableDetailedErrors = true;
config.EnableJavaScriptProxies = true;
app.MapSignalR("/signalr", config);
}
}
}
Have my chatHub class with my methods inside:
[HubName("chatHub")]
public class ChatHub : Hub
{
}
I have a javascript file named chatboxManager with the following inside:
var connection = $.hubConnection();
var ChatHub = connection.createHubProxy('chatHub');
Using the above I get a connection to the chatHub
but it does not recognise the .client the bellow:
// On New User Connected
debugger;
ChatHub.client.onNewUserConnected = function (id, name, userid) {
AddUser(ChatHub, id, name, userid);
}
If I use this at the beginning of the js file nothing works:
var ChatHub = $.connection.chatHub;
Is there something else that I could be missing?
I have de-installed the packages and re-installed them.
Any advice would greatly be appreciated to get this running.
Kind regards and thanks
I dont know if this might be the solution but give it a try
var hubConnection = new HubConnection("http://yourIpHere:yourPortNr/signalr");
var chatHubProxy = hubConnection.CreateHubProxy("chatHub");

(Apache Wicket) Set java atrribute from a js function

I am brand new on Apache Wicket and I need to set value on a Java attribute. This value comes from a var on JS filled by a specific function from a specific GIS lib (https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html). This setting must be triggered by some component behavior.
Here is a simplified example code:
Wicket web page:
public class MapPage extends WebPage {
private static final long serialVersionUID = 1L;
private Integer coordinates;
// getters and setters
}
Wicket html:
<html xmlns:wicket="http://wicket.apache.org">
<head>
<!-- metas, scripts, and css imports -->
</head>
<body>
<script>
// component declarations
var coordinates = ''
map.on('draw:edited', function (e) {
e.layers.eachLayer(function(layer) {
coordinates = toWKT(layer);
// send coordinates to coordinates java attribute ??? how??
});
});
</script>
</body>
Thanks a lot!
This is a piece of code from one of my projects, where I want to handle a click on a (HighCharts) chart. It passes data to Wicket and Wicket then updates another panel to display details related to the click.
The relevant javascript part, where interactionurl is actually the callbackScript that is generated by the behavior later on:
interactionurl(JSON.stringify(myDataToPass));
The behaviour:
this.add( this.interactionbehavior = new AbstractDefaultAjaxBehavior()
{
#Override
protected void respond( final AjaxRequestTarget target )
{
RequestCycle cycle = RequestCycle.get();
WebRequest webRequest = (WebRequest) cycle.getRequest();
String param1 = webRequest.getQueryParameters().getParameterValue( "mydict" ).toString( "" );
//param1 contains the JSON map passed from javascript.
//you can also do stuff now, like replacing components using ajax
}
#Override
protected void updateAjaxAttributes( AjaxRequestAttributes attributes )
{
super.updateAjaxAttributes( attributes );
attributes.getExtraParameters().put( "mydict", "__PLACEHOLDER__" );
}
#Override
public CharSequence getCallbackScript()
{
String script = super.getCallbackScript().toString().replace( "\"__PLACEHOLDER__\"", "data" );
return script;
}
} );
You only need to pass the interaction url to the page on some moment. For this you can use renderHead in the component that has the behaviour:
#Override
public void renderHead( final IHeaderResponse response )
{
...
//use the `setupCallback` to store the callback script somewhere.., I store it in 'interactionurl'
String script = String.format( " setupCallback(this.interactionbehavior.getCallbackScript()); ");
response.render( OnDomReadyHeaderItem.forScript( script )
}

Load a new page in JavaFX webview

I am currently working on a Java application that uses a JavaFX webview to display its UI (with HTML/CSS).
Everything is working fine but I have trouble loading a new page in the system. When I do, the communication between the Java and the new page's JavaScript seems to be broken.
Here is my code :
** Broser **
public class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser() {
//apply the styles
getStyleClass().add("browser");
// load the web page
webEngine.load(some_url);
JSObject jsobj = (JSObject) webEngine.executeScript("window");
Bridge bridge = Bridge.getInstance();
bridge.init(webEngine);
jsobj.setMember("java", bridge);
//add the web view to the scene
getChildren().add(browser);
}
}
** Bridge **
public class Bridge {
private static Bridge instance = null;
private WebEngine webEngine;
public Bridge () {
}
public static Bridge getInstance() {
if(instance == null){
instance = new Bridge();
}
return instance;
}
public void init(WebEngine webEngine) {
if(this.webEngine == null) {
this.webEngine = webEngine;
}
}
public void btnStartSessionOnClick(String sessionName, String speakerNickname) {
// Load the new page
webEngine.load(some_other_url);
}
}
Whenever the web engine loads a new page, it replaces the DOM, so there is a different window object. The jsobj you define is only set once, so when a new page is loaded it will be pointing to the wrong object. You need to reset this object every time the page loads, which you can do by observing the engine's load state.
Your design doesn't make a whole lot of sense to me: it makes more sense to me to have the window (jsobj) object as part of the Bridge class, rather than the application class. And since the Browser is not a singleton, it doesn't make sense to make the Bridge a singleton (what if you had multiple web views in your application, for example?).
Here's an SSCCE:
package application;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewTest extends Application {
#Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
Label output = new Label();
Bridge bridge = new Bridge(engine);
engine.load(getClass().getResource("/resources/First.html").toExternalForm());
Button first = new Button("Load First");
first.setOnAction(e -> engine.load(getClass().getResource("/resources/First.html").toExternalForm()));
Button second = new Button("Load Second");
second.setOnAction(e -> engine.load(getClass().getResource("/resources/Second.html").toExternalForm()));
TextField textField = new TextField();
Button button = new Button("Send");
EventHandler<ActionEvent> handler = e -> {
bridge.execute(result -> output.setText(result.toString()),
"showText", textField.getText());
textField.setText("");
};
button.setOnAction(handler);
textField.setOnAction(handler);
HBox controls = new HBox(5, first, second, textField, button, new Label("Web page says: "), output);
controls.setPadding(new Insets(10));
BorderPane root = new BorderPane(webView, null, null, controls, null);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The Bridge class:
package application;
import java.util.function.Consumer;
import javafx.concurrent.Worker.State;
import javafx.scene.web.WebEngine;
import netscape.javascript.JSObject;
public class Bridge {
private JSObject window ;
public Bridge(WebEngine engine) {
engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
if (newState == State.SUCCEEDED) {
window = (JSObject) engine.executeScript("window");
window.setMember("application", this);
}
});
}
public void execute(Consumer<Object> callback, String function, Object... args) {
callback.accept(window.call(function, args));
}
}
And some simple test HTML files, which I have in a resources folder in the root of the classpath.
First.HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>First</title>
<script>
function showText(text) {
document.getElementById("text").innerHTML = text;
return text;
}
</script>
</head>
<body>
<p>This is the first page</p>
Go to the second page
<div id="text"></div>
</body>
</html>
and Second.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Second</title>
<script>
function showText(text) {
document.getElementById("text").innerHTML = text;
return text;
}
</script>
</head>
<body>
<p>This is the second page</p>
Go back to the first page
<div id="text"></div>
</body>
</html>

Mark of the Web on Xpages

So I need to send an attachment to a document, but I have to validate if it is larger than 15mb , for so I am using this code in javascript to get the file :
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = document.getElementById(fileid).value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
I'm having an error when I try to create ActiveXObject because my site is not "trusted " by not having a Mark of the Web
<!doctype html>
<!-- saved from url=(0023)http://www.contoso.com/ -->
<html>
<head>
<title>A Mark of the Web Example.</title>
</head>
<body>
<p>Hello, World</p>
</body>
</html>
so I wonder if it is possible to have a mark of the web in a XPage and how I could put it the body of the XPage.
My client does not want to manually place the security option , but want to use IE , please help me haha.
If there is another way to check the file size when selecting a file using javascript would be interesting.
Try this code to check file size in HTML5 should work in all modern browsers
var fileSize=0
if (typeof FileReader !== "undefined") {
var filePath = document.getElementById(fileid);
fileSize= filePath.files[0].size;
}
Check the filesize var for the max limit of you file.
Use this code if the browser is IE10 or newer and your old code if the browser is older.
You can create a Java validator for old browsers, but if the Javascript API is available (modern browsers), use it.
public class Attachment implements Validator {
private final static long BYTES_IN_1_MB = 1048576;
private final static long MAX_MB_ALLOWED = 10;
private final static String MSG_ERROR_SIZE = "File size cannot be bigger than {0} MBs";
public void validate(FacesContext fc, UIComponent uiComp, Object attach)
throws ValidatorException {
FacesMessage msg;
UploadedFile upFile = (UploadedFile) attach;
long max_bytes = BYTES_IN_1_MB * MAX_MB_ALLOWED;
// SIZE:
if (upFile.getContentLength() > max_bytes) {
String msgError = MSG_ERROR_SIZE.replace("{0}", String.valueOf(MAX_MB_ALLOWED));
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgError, msgError);
throw new ValidatorException(msg);
}
}
}
These validators need to be added into the faces-config.xml
<validator>
<validator-id>attachmentValidator</validator-id>
<validator-class>com.faces.validator.Attachment</validator-class>
</validator>
Then you can add the validator into the fileUpload field:
<xp:this.validators>
<!-- Validator for Attachments -->
<xp:validator validatorId="attachmentValidator">
</xp:validator>
</xp:this.validators>

Categories