I have a simple flex3 project with and mxml file (with some as inside of it) and FMSConnection.as
I have something like this
public class FMSConnection extends NetConnection
{
//this methods is called from the media server
public function Message(message:String):void
{
//how to display (add it to a textarea) this message, when this method is invoked ?
}
}
//in the mxml, after FMSConnection is created:
fmsConn.addEventListener(FMSConnection.MESSAGE_RECEIVED, onMessage);
private function onMessage(e:Event):void
{
fmsConn = FMSConnection(e.target);
textArea.text += fmsConn.lastMessage;
}
//FMSConnection
public class FMSConnection extends NetConnection
{
public static const MESSAGE_RECEIVED:String = "messageReceived";
public var lastMessage:String;
public function Message(message:String):void
{
lastMessage = message;
dispatchEvent(new Event(MESSAGE_RECEIVED));
}
}
Instead of declaring the lastMessage variable, you can dispatch a custom event and store the message in it if you want to.
//MsgEvent.as
public class MsgEvent extends Event
{
public static const MESSAGE_RECEIVED:String = "messageReceived";
public var message:String;
public function MsgEvent(message:String, type:String)
{
super(type);
this.message = message;
}
override public function clone():Event
{
return new MsgEvent(message, type);
}
}
//in the mxml, after FMSConnection is created:
fmsConn.addEventListener(MsgEvent.MESSAGE_RECEIVED, onMessage);
private function onMessage(e:MsgEvent):void
{
textArea.text += e.message;
}
//FMSConnection
public class FMSConnection extends NetConnection
{
public function Message(message:String):void
{
dispatchEvent(new MsgEvent(message, MsgEvent.MESSAGE_RECEIVED));
}
}
Overriding the clone method is not necessary in this case, but it's a good practice to follow while using custom events. If you don't override the clone method, you will get a runtime error while trying to redispatch the custom event from the event handler.
Related
I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.
I am having a problem that is driving me nuts.
Recently I configured my BlazeDS to use Array instead of ArrayCollection for performance reasons. Additionally I adjusted my templates to generate Array properties.
Everything wen't fine. All except one function that causes TypeError: Error #1034. These are being thrown before the result callback is called. It claims to have problems casting an ArrayCollection to Array. I removed the generated types to make Flex use Objects instead, but these did not contain any ArrayCollections. My question now is: How can I get the stack-traces of errors thrown in event-handlers?
I allready added handlers for unhandledExceptions in all of my modules and they are called if errors occur in code triggered from user-interaction, but they don't seem to be able to catch stuff thrown by event-handlers.
How can I track these Errors?
Chris
PS: The classes are:
package de.upw.ps.ucg.model.ucg.scheduler {
[Bindable]
[RemoteClass(alias="de.upw.ps.ucg.model.ucg.scheduler.Task")]
public class Task extends TaskBase {
}
}
And:
package de.upw.ps.ucg.model.ucg.scheduler {
import de.upw.ps.ucg.model.oval.common.OvalVersionedIdentifier;
import flash.utils.IExternalizable;
[Bindable]
public class TaskBase {
public function TaskBase() {}
private var _aborted:Boolean;
private var _characteristicsId:String;
private var _currentExecutorPhase:JobExecutorPhase;
private var _definitionSetName:String;
private var _definitionSetVid:OvalVersionedIdentifier;
private var _endTime:Date;
private var _enqueueTime:Date;
private var _environmentId:String;
private var _environmentName:String;
private var _messages:Array;
private var _numberOfDefinitions:int;
private var _processedNumberOfTests:int;
private var _resultsId:String;
private var _schedulerJob:SchedulerJob;
private var _startTime:Date;
private var _statusMessage:String;
private var _taskId:String;
private var _totalNumberOfTests:int;
public function set aborted(value:Boolean):void {
_aborted = value;
}
public function get aborted():Boolean {
return _aborted;
}
public function set characteristicsId(value:String):void {
_characteristicsId = value;
}
public function get characteristicsId():String {
return _characteristicsId;
}
public function set currentExecutorPhase(value:JobExecutorPhase):void {
_currentExecutorPhase = value;
}
public function get currentExecutorPhase():JobExecutorPhase {
return _currentExecutorPhase;
}
public function set definitionSetName(value:String):void {
_definitionSetName = value;
}
public function get definitionSetName():String {
return _definitionSetName;
}
public function set definitionSetVid(value:OvalVersionedIdentifier):void {
_definitionSetVid = value;
}
public function get definitionSetVid():OvalVersionedIdentifier {
return _definitionSetVid;
}
public function set endTime(value:Date):void {
_endTime = value;
}
public function get endTime():Date {
return _endTime;
}
public function set enqueueTime(value:Date):void {
_enqueueTime = value;
}
public function get enqueueTime():Date {
return _enqueueTime;
}
public function set environmentId(value:String):void {
_environmentId = value;
}
public function get environmentId():String {
return _environmentId;
}
public function set environmentName(value:String):void {
_environmentName = value;
}
public function get environmentName():String {
return _environmentName;
}
public function set messages(value:Array):void {
_messages = value;
}
public function get messages():Array {
return _messages;
}
public function set numberOfDefinitions(value:int):void {
_numberOfDefinitions = value;
}
public function get numberOfDefinitions():int {
return _numberOfDefinitions;
}
public function set processedNumberOfTests(value:int):void {
_processedNumberOfTests = value;
}
public function get processedNumberOfTests():int {
return _processedNumberOfTests;
}
public function set resultsId(value:String):void {
_resultsId = value;
}
public function get resultsId():String {
return _resultsId;
}
public function set schedulerJob(value:SchedulerJob):void {
_schedulerJob = value;
}
public function get schedulerJob():SchedulerJob {
return _schedulerJob;
}
public function set startTime(value:Date):void {
_startTime = value;
}
public function get startTime():Date {
return _startTime;
}
public function set statusMessage(value:String):void {
_statusMessage = value;
}
public function get statusMessage():String {
return _statusMessage;
}
public function set taskId(value:String):void {
_taskId = value;
}
public function get taskId():String {
return _taskId;
}
public function set totalNumberOfTests(value:int):void {
_totalNumberOfTests = value;
}
public function get totalNumberOfTests():int {
return _totalNumberOfTests;
}
}
}
Both classes are generated by my maven build from a corresponding Java Class and the Types do fit together nicely.
Do you have access to the socket class that's reading in all these messages? Trace out the buffer before the deserialisation and you should at least be able to find the class that's giving you hassle.
Failing that, trace out the object after deserialisation and it should be the very first one after the error is thrown.
This is something you'll have to debug on your own, but I have a gut feeling that the problem is because the data being sent by your java DTO is not the same as your AS3 class, even though that you have the RemoteClass metadata saying that it is.
Are you missing a property? or have a property mismatch? That is the most likely cause of your error. I suggest you debug the java side as much as you can and use something like firebug to see the request/response of the server.
Hey,
I am trying to return a user defined class from a web method. The class has properties and/or methods.
Given the following web method:
[WebMethod]
public List<MenuItem> GetMenu()
{
List<MenuItem> menuItemList = new List<MenuItem>();
menuItemList.Add(new MenuItem());
menuItemList.Add(new MenuItem());
menuItemList.Add(new MenuItem());
return menuItemList;
}
Now, suppose this web service is consumed by adding a web reference in a newly created console application. The following code is used to test it:
public void TestGetMenu()
{
MenuService service = new MenuService.MenuService();
service.MenuItem[] menuItemList = service.GetMenu();
for (int i = 0; i < menuItemList.Length; i++)
{
Console.WriteLine(menuItemList[i].name);
}
Console.ReadKey();
}
First of all, this doesn't work if the MenuItem class contains properties... Also, if the MenuItem class contains a method the call to the web method doesn't fail, but the method is not in the generated proxy class.. for example: menuItemList[i].getName() does not exist. Why? What am i missing?
//This works
public class MenuItem
{
public string name;
public MenuItem()
{
name = "pizza";
}
}
//This crashes / doesnt work
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string Name
{
get { return name; }
set { name = value; }
}
}
//This successfully calls web method, but the method does not exist during test
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string getName()
{
return name;
}
}
It will only work if the class is serializable which usually means public fields and properties, this is why your MenuItem will fail because your client side has no idea how to construct the MenuItem class properly.
Try this:
[Serializable]
public class MenuItem
{
private string name;
public MenuItem()
{
name = "pizza";
}
public string Name
{
get {
return name;
}
set {
name = value;
}
}
}
private properties are not sent to the client if I remember right.
Methods cannot be generated on the client. What is a method used some resources on the server?
2a. To work around this, you can use partial classes to reimplement some of the methods.
I know actionscript does not allowed private contstructor at any time and But if i want to write a sinlgleton class in action script So how to implement it in actionscript.
Can anyone provide an sample example of a singleton pattern in actionscript?
I use something like this:
package singletons
{
[Bindable]
public class MySingleton
{
private static var _instance:MySingleton;
public function MySingleton(e:Enforcer) {
if(e == null) {
throw new Error("Hey! You can't do that! Call getInstance() instead!");
}
}
public static function getInstance():MySingleton {
if(_instance == null) {
_instance = new MySingleton (new Enforcer);
}
return _instance;
}
}
}
// an empty, private class, used to prevent outside sources from instantiating this locator
// directly, without using the getInstance() function....
class Enforcer{}
You need to alter Alxx's answer slightly as it doesn't stop new Singleton() from working...
public class Singleton {
private static var _instance : Singleton;
public function Singleton( newBlocker : ClassLock ) {
}
public static function getInstance() : Singleton {
if ( _instance == null ) {
_instance = new Singleton( new ClassLock() );
}
return _instance;
}
}
class ClassLock{}
The private class is used by the Singleton to stop other classes simply doing new Singleton() initially and then getting a second instance by doing getInstance().
Note that this still isn't watertight... If someone is determined to break it, they can get access to the private class, but this is about the best option for Singletons.
basically, all answers are right, those of reid and gregor provide more compile time safety. I suppose, the best thing is however, to declare an interface for the singleton and a private implementor exposed through a static class:
package {
interface IFoo {
function foo():void;
}
}
and then:
package Foo {
private static var _instance:IFoo;
public static function getInstance():IFoo {
if (_instance == null) _instance = new Impl();
return _instance;
}
}
class Impl implements IFoo {
public function foo():void {
trace("fooooooooooooooooooo");
}
}
this doesn't rely on runtime errors for safety. Also, it lowers coupling.
greetz
back2dos
public class Singleton {
private static var _instance:Singleton;
public **static** function get instance():Singleton
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public function Singleton()
{
if (_instance != null) throw new Error("You can't create Singleton twice!");
}
}
Runtime check in lack of private constructor.
I use this approach ...
package
{
public class Main
{
private static var _instance:Main;
private static var _singletonLock:Boolean = false;
/**
* Creates a new instance of the class.
*/
public function Main()
{
if (!_singletonLock) throw new SingletonException(this);
}
/**
* Returns the singleton instance of the class.
*/
public static function get instance():Main
{
if (_instance == null)
{
_singletonLock = true;
_instance = new Main();
_singletonLock = false;
}
return _instance;
}
}
}
... not as terse as some other methods but it's absolutely safe and there's no need for an empty package-level class. Also note the shortcut with SingletonException which is a class that extends the AS3 Error class and saves typing some code when using more than one Singleton ...
package
{
public class SingletonException extends Error
{
public function SingletonException(object:Object)
{
super("Tried to instantiate the singleton " + object + " through it's constructor."
+ " Use the 'instance' property to get an instance of this singleton.");
}
}
}
I have a collection of objects and each object throws an event every time its value gets updated. Im trying to capture that event by adding a listener to the arraycollection that holds it (see main class) but its not working. Honestly I'm not sure this is the correct approach.
I'm avoiding using Collection.CHANGE because it fells into an infinite recursion ultimately ends in a stack overflow. Any ideas?
[Bindable]
public class NamesVO {
public var steveList:ArrayCollection; // array of SteveVO objects
public function NamesVO() {
steveList = new ArrayCollection();
}
public function rename():void {
for each(var steve:SteveVO in steveList) {
steve.rename();
}
}
}
[Bindable]
public class SteveVO extends EventDispatcher {
public static const VALUE_CHANGED:String = "VALUE_CHANGED";
public var code:String;
public var name:String;
public var _quantity:Number;
public function SteveVO() {
this.code = "";
this.name = "";
_quantity = 0;
}
public function get quantity():Number {
return _quantity;
}
public function set quantity(quantity:Number):void {
_quantity = quantity;
dispatchEvent(new Event(VALUE_CHANGED));
}
public function rename():void {
name = code + " - " + _quantity;
}
}
Main class:
names = new NamesVO();
names.steveList.addEventListener(SteveVO.VALUE_CHANGED, function():void {
names.rename(); // this anon function is not being executed!!
});
var steve:SteveVO = new SteveVO();
names.steveList.addItem(steve);
// names is bound on a datagrid and uses itemeditor for each SteveVO object
The VALUE_CHANGED event is not dispatched by the steveList array Collection so won't be detected by your listener. You could encapsulate the functionality you want inside the NamesVO class by detecting when an item is added to the array collection and adding a listener to the new steveVO object that dispatches the same event from NamesVO. Then just listen for that event in your main class.
Is there a reason to change all the names when one quantity is changed. Would it be better simply to call rename inside the set function of the steveVO class?
To implement the change:
import flash.events.Event;
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
[Bindable]
public class namesVO
{
public var steveList:ArrayCollection; // array of SteveVO objects
public function namesVO()
{
steveList = new ArrayCollection();
steveList.addEventListener(CollectionEvent.COLLECTION_CHANGE,collChanged);
}
private function collChanged(e:CollectionEvent):void
{
if (e.kind == CollectionEventKind.ADD)
e.items[0].addEventListener(steveVO.VALUE_CHANGED,valueChanged);
}
private function valueChanged(e:Event):void
{
dispatchEvent(new Event(steveVO.VALUE_CHANGED));
}
public function rename():void
{
for each(var steve:steveVO in steveList)
{
steve.rename();
}
}
}
In the main class use:
names = new namesVO();
names.addEventListener(steveVO.VALUE_CHANGED, function():void
{
names.rename();
});
steve = new steveVO();
names.steveList.addItem(steve);
steve.quantity = 12;
Of course this is only an example and only includes the case where one item is added at a time.